Wild card matching
Given an input string (s) and a pattern (p), implement wildcard pattern matching with support for '?' and '*' where:
'?'Matches any single character.'*'Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
Example 1:
Input: s = "aa", p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".Example 2:
Input: s = "aa", p = "*"
Output: true
Explanation: '*' matches any sequence.Example 3:
Input: s = "cb", p = "?a"
Output: false
Explanation: '?' matches 'c', but the second letter is 'a', which does not match 'b'.Example 4:
Input: s = "adceb", p = "*a*b"
Output: true
Explanation: The first '*' matches the empty sequence, while the second '*' matches the substring "dce".Explanation
State Transition
Case 1: If the current pattern character matches the current input character or is a '?", mark the current cell as true.
Case 2: If the current pattern character is a '*', mark the current cell as true if
[null match] the current input character can be matched by the previous pattern character
M[i][j] = M[i][j-1]
OR
[1+ match] the current character can be matched by the '*' if last input char is_match
can be thought of as "skipping" over the current input character
M[i][j] = M[i-1][j]
Case 3: No match
State Definition
i (int)
the index up to which the input is matched
j (int)
the index up to which the pattern is matched
is_match (bool):
True if for the given i, j the pattern+input substrings are a match
State Initialization (base case)
i=0, j=0 is true
empty pattern matches the empty string
i>0, j=0 is false
empty pattern cannot match non-empty string
i=0, j>0 is true if the current pattern character is '*' and the previous is also a match
can be thought of as a 'leading asterisk' case
any leading characters which can match an empty string are true. Otherwise false
TC: O(N^2)
SC: O(N^2) can be lowered to O(2N) as only two rows are relevant
Last updated
Was this helpful?