LeetCode 20. Valid Parentheses in F#

URL

Valid Parentheses - LeetCode

Code

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

let isValid (s: string) : bool =
    let rec isValid' cs acc =
        match cs with
        | [] ->
            match acc with
            | [] -> true
            | _ -> false
        | h :: t ->
            match h with
            | '('
            | '['
            | '{' -> isValid' t (h :: acc)
            | ')' ->
                match List.tryHead acc with
                | Some(v) when v = '(' -> isValid' t (List.tail acc)
                | _ -> false
            | ']' ->
                match List.tryHead acc with
                | Some(v) when v = '[' -> isValid' t (List.tail acc)
                | _ -> false
            | '}' ->
                match List.tryHead acc with
                | Some(v) when v = '{' -> isValid' t (List.tail acc)
                | _ -> false
            | _ -> failwith "never reach here"

    isValid' (Seq.toList s) []