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:
Example 2:
Example 3:
Example 4:
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?