Skip to content

Instantly share code, notes, and snippets.

@ebresafegaga
Last active February 14, 2022 19:22
Show Gist options
  • Save ebresafegaga/cc6b931ee3e8128bb128e9d5b52fa9dc to your computer and use it in GitHub Desktop.
Save ebresafegaga/cc6b931ee3e8128bb128e9d5b52fa9dc to your computer and use it in GitHub Desktop.
Leetcode wildcard matching solution in F#. https://leetcode.com/problems/wildcard-matching/
type pattern =
| Char of char * pattern
| Any of pattern
| Wildcard of pattern
| End
let parsePattern (str: string) =
let str = [for s in str do s]
let folder c pat =
match c with
| '?' -> Any pat
| '*' -> Wildcard pat
| c -> Char (c, pat)
List.foldBack folder str End
let matches c = function
| Char (x, _) -> x = c
| Any _ -> true
| Wildcard _ -> true
| End -> false
let rec is_match str pat =
match str, pat with
| c :: str, Char (x, pat) -> c = x && is_match str pat
| _any :: str, Any pat -> is_match str pat
| [], Wildcard End -> true
| c :: str, Wildcard pat -> is_match (c :: str) pat || is_match str (Wildcard pat)
| _c :: _str, End -> false
| [], End -> true
| [], Char _ | [], Any _ | [], Wildcard _ -> false
let isMatch (str: string) pat =
is_match [for s in str do s] (parsePattern pat)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment