LeetCode 2337. Move Pieces to Obtain a String in F#

URL

https://leetcode.com/problems/move-pieces-to-obtain-a-string/description/?envType=daily-question&envId=2024-12-05

Code

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

let canChange (start: string) (target: string) : bool =
    let rec canChange' cs1 cs2 =
        match cs1, cs2 with
        | [], [] -> true
        | [], _
        | _, [] -> failwith "never reach here"
        | (i1, h1) :: t1, (i2, h2) :: t2 ->
            if h1 <> h2 || (h1 = 'L' && i1 < i2) || (h1 = 'R' && i1 > i2) then
                false
            else
                canChange' t1 t2

    let nonEmptyPositions (s: string) =
        s |> Seq.indexed |> Seq.filter (fun (_, c) -> c <> '_') |> Seq.toList

    let cs1 = nonEmptyPositions start
    let cs2 = nonEmptyPositions target
    if List.length cs1 <> List.length cs2 then
        false
    else
        canChange' cs1 cs2