Wildcard matching
Hard TimeO(n·m) SpaceO(n·m)
Match a string s against a pattern p where ? matches exactly one character, never zero, and * matches any run of characters, an empty one included. Unlike the regular-expression form, a * here stands alone rather than repeating the character before it. The match must cover the whole string.
Examples
Example 1
- Input
- s = "adceb"p = "*a*b"
- Output
- The first
true*takes nothing,amatchesa, the second*takesdce, andbmatchesb.
Example 2
- Input
- s = "acdcb"p = "a*c?b"
- Output
falseamatches, but nothing the*can take leavesc?bexactly three characters to finish on.
The Code
function isMatch(s, p) {
const dp = [];
for (let i = 0; i <= s.length; i++) {
dp.push(new Array(p.length + 1).fill(false));
}
dp[0][0] = true;
for (let j = 1; j <= p.length; j++) {
if (p[j - 1] === "*") dp[0][j] = dp[0][j - 1];
}
for (let i = 1; i <= s.length; i++) {
for (let j = 1; j <= p.length; j++) {
if (p[j - 1] === "*") {
dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
} else if (p[j - 1] === "?" || p[j - 1] === s[i - 1]) {
dp[i][j] = dp[i - 1][j - 1];
}
}
}
return dp[s.length][p.length];
}
isMatch("adceb", "*a*b");Done
The first 12 calls, of 44. This one does not fit on a page.
More like this
All dynamic programming examples (20) →- Climbing stairs Count the ways to the top — Fibonacci in disguise.
- Coin change Try every coin and keep the cheapest way to make the amount.
- Max subarray One pass, two running totals — Kadane’s algorithm.
- LCS Match a character or drop one from either string.
- Edit distance Insert, delete, or replace — take the cheapest at each mismatch.
- 0/1 Knapsack For each item, take it or leave it — keep the more valuable branch.