Shohei Yoshida
Shohei Yoshida's Blog

Follow

Shohei Yoshida's Blog

Follow

290. Word Pattern in F#

Shohei Yoshida's photo
Shohei Yoshida
·Jan 1, 2023·

1 min read

URL

https://leetcode.com/problems/word-pattern/description/

Code

https://github.com/syohex/dotnet-study/blob/master/fsharp/leetcode/problems/0290/main.fsx

let wordPattern (pattern: string) (s: string) : bool =
    let rec wordPattern' pattern words m registered =
        match pattern, words with
        | [], [] -> true
        | p1 :: t1, word :: t2 ->
            match Map.tryFind p1 m with
            | Some (v) ->
                if word <> v then
                    false
                else
                    wordPattern' t1 t2 m registered
            | None ->
                if Set.contains word registered then
                    false
                else
                    wordPattern' t1 t2 (Map.add p1 word m) (Set.add word registered)
        | _, _ -> failwith "never reach here"

    let words = s.Split ' '

    if pattern.Length <> words.Length then
        false
    else
        wordPattern' (pattern |> Seq.toList) (words |> Array.toList) Map.empty Set.empty
 
Share this