LeetCode 1415. The k-th Lexicographical String of All Happy Strings of Length n in F#

URL

https://leetcode.com/problems/the-k-th-lexicographical-string-of-all-happy-strings-of-length-n/description/?envType=daily-question&envId=2025-02-19

Code

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

let getHappyString (n: int) (k: int) : string =
    let rec f pos prev (acc: char list) cands =
        if pos = n then
            (acc |> List.rev |> System.String.Concat) :: cands
        else
            "abc"
            |> Seq.fold (fun cands c -> if c = prev then cands else f (pos + 1) c (c :: acc) cands) cands

    f 0 '?' [] [] |> List.rev |> List.tryItem (k - 1) |> Option.defaultValue ""