Shohei Yoshida
Shohei Yoshida's Blog

Shohei Yoshida's Blog

LeetCode 890. Find and Replace Pattern in F#

Shohei Yoshida's photo
Shohei Yoshida
·Jul 29, 2022·

1 min read

URL

leetcode.com/problems/find-and-replace-patt..

Code

github.com/syohex/dotnet-study/blob/master/..

let findAndReplacePattern (words: string list) (pattern: string) : string list =
    let toIndexPattern word =
        let rec toIndexPattern' cs i cache acc =
            match cs with
            | [] -> acc |> List.rev
            | h :: t ->
                match Map.tryFind h cache with
                | Some (pos) -> toIndexPattern' t (i + 1) cache (pos :: acc)
                | None -> toIndexPattern' t (i + 1) (Map.add h i cache) (i :: acc)

        toIndexPattern' (word |> Seq.toList) 0 Map.empty []

    let pp = toIndexPattern pattern

    words
    |> List.filter (fun word ->
        let wp = toIndexPattern word

        List.zip pp wp
        |> List.forall (fun (a, b) -> a = b))
 
Share this