LeetCode 2109. Adding Spaces to a String in F#

URL

https://leetcode.com/problems/adding-spaces-to-a-string/description/?envType=daily-question&envId=2024-12-03

Code

https://github.com/syohex/dotnet-study/blob/master/fsharp/leetcode/challenge/202412/adding_spaces_to_a_string/main.fsx

open System

let addSpaces (s: string) (spaces: int list) : string =
    let rec addSpaces' cs spaces (acc: char list) =
        match cs, spaces with
        | [], [] -> acc |> List.rev |> String.Concat
        | [], _ -> failwith "never reach here"
        | (_, h) :: t, [] -> addSpaces' t [] (h :: acc)
        | (i, c) :: t1, j :: t2 ->
            if i = j then
                addSpaces' t1 t2 (c :: ' ' :: acc)
            else
                addSpaces' t1 spaces (c :: acc)

    let cs = s |> Seq.indexed |> Seq.toList
    addSpaces' cs spaces []