LeetCode 3163. String Compression III in F#

URL

https://leetcode.com/problems/string-compression-iii/description/?envType=daily-question&envId=2024-11-04

Code

https://github.com/syohex/dotnet-study/tree/master/fsharp/leetcode/challenge/202411/string_compression3/main.fsx

open System

let compressedString (word: string) : string =
    let numToChar (n: int) = char <| n + int '0'

    let rec compressedString' cs prev count (acc: char list) =
        match cs with
        | [] -> (prev :: numToChar count :: acc) |> List.rev |> String.Concat
        | h :: t ->
            if count = 9 then
                compressedString' t h 1 (prev :: '9' :: acc)
            elif h = prev then
                compressedString' t prev (count + 1) acc
            else
                compressedString' t h 1 (prev :: numToChar count :: acc)

    match Seq.toList word with
    | [] -> failwith "never reach here"
    | h :: t -> compressedString' t h 1 []