Wildcard Matching
Difficulty: Hard · Pattern: 2-D Dynamic Programming · LeetCode #44
Implement wildcard matching with ? (any single character) and * (any sequence, including the empty one). The match must cover the entire string.
Examples
text
s = "aa", p = "a" → false
s = "aa", p = "*" → true
s = "cb", p = "?a" → false
s = "adceb", p = "*a*b" → true
s = "acdcb", p = "a*c?b" → falseHints
- It looks like Regex Matching, but here
*stands on its own and matches any run of characters. dp[i][j]: a*either matches nothing (dp[i][j−1]) or swallowss[i−1]and stays available (dp[i−1][j]).
Approach
DP:
text
dp[0][0] = True; dp[0][j] = dp[0][j-1] and p[j-1] == '*'
p[j-1] == '*': dp[i][j] = dp[i][j-1] or dp[i-1][j]
p[j-1] in (s[i-1], '?'): dp[i][j] = dp[i-1][j-1]That's O(m·n) and rolls into 1-D.
Greedy two-pointer (O(m·n) worst case, often linear): remember the position of the last * and the position in s where it started matching. On a mismatch, backtrack by letting that * absorb one more character. This version is the usual follow-up.
Complexity
Time: O(m·n). Space: O(n) for the DP, O(1) for the greedy.
Python solution
def isMatch(s, p):
m, n = len(s), len(p)
dp = [False] * (n + 1)
dp[0] = True
for j in range(1, n + 1):
dp[j] = dp[j - 1] and p[j - 1] == '*'
for i in range(1, m + 1):
diag, dp[0] = dp[0], False
for j in range(1, n + 1):
tmp = dp[j]
if p[j - 1] == '*':
dp[j] = dp[j - 1] or dp[j]
else:
dp[j] = diag and p[j - 1] in (s[i - 1], '?')
diag = tmp
return dp[n]JavaScript solution
function isMatch(s, p) {
// Greedy with backtracking to the last '*'.
let i = 0, j = 0, star = -1, mark = 0;
while (i < s.length) {
if (j < p.length && (p[j] === '?' || p[j] === s[i])) { i++; j++; }
else if (j < p.length && p[j] === '*') { star = j++; mark = i; }
else if (star !== -1) { j = star + 1; i = ++mark; }
else return false;
}
while (j < p.length && p[j] === '*') j++;
return j === p.length;
}