Regular expression matching
Hard TimeO(n·m) SpaceO(n·m)
Match a string s against a pattern p where . matches any single character and * matches zero or more of the character immediately before it. The match must cover the whole string, not merely a part of it. A * always follows a character, and may match zero occurrences of it.
Examples
Example 1
- Input
- s = "aab"p = "c*a*b"
- Output
truec*takes nocat all,a*takes bothas, andbmatchesb.
Example 2
- Input
- s = "aa"p = "a"
- Output
- The pattern accounts for one
falseaand leaves the second over; a partial match does not count.
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 - 2];
}
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][j - 2];
if (p[j - 2] === "." || p[j - 2] === s[i - 1]) {
if (dp[i - 1][j]) dp[i][j] = true;
}
} 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("aab", "c*a*b");Done
The first 12 calls, of 34. 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.