Regular Expression Matching (LeetCode 10): Solution and Explanation
Implement full-string matching for a pattern that supports ., which matches any one character, and *, which matches zero or more copies of the element right before it. The whole input string must be matched, not just a part of it.
Watch it run step by step
Try your own input and write the code →Intuition
Without * this is trivial: walk both strings and compare character by character, treating . as a wildcard. The star is what makes it hard, because a* can consume zero, one or many characters and you cannot tell locally which choice is right. Trying all choices recursively works but can branch exponentially on patterns like a*a*a*b.
Those choices revisit the same pairs of positions, so cache them. Let dp[i][j] mean the first i characters of s match the first j characters of p. If p[j-1] is a plain letter or ., it must match s[i-1], and the rest reduces to dp[i-1][j-1]. If p[j-1] is *, treat x* as a unit with two options. Use it zero times, which means skipping both pattern characters: dp[i][j-2]. Or, if x matches s[i-1], let it absorb that character and stay on the same pattern position: dp[i-1][j].
The second option is what makes * repeatable without enumerating counts. Each time it eats one character it lands on a smaller subproblem that can choose again. The only special base case is the empty string, which can still be matched by patterns like a*b* where every starred element is used zero times.
Approach: 2D dynamic programming on prefixes
- Create an
(m + 1)by(n + 1)table ofFalseand setdp[0][0] = True. - Fill row 0: for each
jfrom 2, ifp[j-1]is*, setdp[0][j] = dp[0][j-2]so patterns likea*b*match the empty string. - For each
ifrom 1 to m andjfrom 1 to n, check whetherp[j-1]is*. - If it is, set
dp[i][j]todp[i][j-2](zero copies) or, whenp[j-2]is.or equalss[i-1], todp[i-1][j](one more copy). - Otherwise, if
p[j-1]is.or equalss[i-1], setdp[i][j] = dp[i-1][j-1]. - Return
dp[m][n].
Step-by-step example
s = "aab", p = "c*a*b"
- Row 0 (empty string) is
[T, F, T, F, T, F]:c*andc*a*can both vanish, butcalone or anything ending inbcannot. - Row 1 (
"a"): column 3 (c*a) copiesdp[0][2] = T. Column 4 (c*a*) is true becauseamatches the starredaanddp[0][4]is true. - Row 2 (
"aa"): column 4 is true again throughdp[1][4], since the star absorbs the seconda. Column 3 is false, asc*acannot cover two letters. - Row 3 (
"aab"): column 5 comparesbwithband copiesdp[2][4] = T. dp[3][5]is true, so the pattern matches:c*takes nothing,a*takesaa, andbtakesb.
Code: Python, Java, C++
1class Solution:
2 def isMatch(self, s: str, p: str) -> bool:
3 m, n = len(s), len(p)
4 dp = [[False] * (n + 1) for _ in range(m + 1)]
5 dp[0][0] = True
6
7 # Handle patterns like a*, a*b*, etc.
8 for j in range(2, n + 1):
9 if p[j - 1] == '*':
10 dp[0][j] = dp[0][j - 2]
11
12 for i in range(1, m + 1):
13 for j in range(1, n + 1):
14 if p[j - 1] == '*':
15 # Zero occurrences OR one+ occurrences
16 dp[i][j] = dp[i][j - 2] or (
17 (p[j - 2] == '.' or p[j - 2] == s[i - 1]) and dp[i - 1][j]
18 )
19 elif p[j - 1] == '.' or p[j - 1] == s[i - 1]:
20 dp[i][j] = dp[i - 1][j - 1]
21
22 return dp[m][n]1class Solution {
2 public boolean isMatch(String s, String p) {
3 int m = s.length(), n = p.length();
4 boolean[][] dp = new boolean[m + 1][n + 1];
5 dp[0][0] = true;
6
7 for (int j = 2; j <= n; j++) {
8 if (p.charAt(j - 1) == '*') dp[0][j] = dp[0][j - 2];
9 }
10
11 for (int i = 1; i <= m; i++) {
12 for (int j = 1; j <= n; j++) {
13 if (p.charAt(j - 1) == '*') {
14 dp[i][j] = dp[i][j - 2] || (
15 (p.charAt(j - 2) == '.' || p.charAt(j - 2) == s.charAt(i - 1)) && dp[i - 1][j]
16 );
17 } else if (p.charAt(j - 1) == '.' || p.charAt(j - 1) == s.charAt(i - 1)) {
18 dp[i][j] = dp[i - 1][j - 1];
19 }
20 }
21 }
22
23 return dp[m][n];
24 }
25}1class Solution {
2public:
3 bool isMatch(string s, string p) {
4 int m = s.length(), n = p.length();
5 vector<vector<bool>> dp(m + 1, vector<bool>(n + 1, false));
6 dp[0][0] = true;
7
8 for (int j = 2; j <= n; j++) {
9 if (p[j - 1] == '*') dp[0][j] = dp[0][j - 2];
10 }
11
12 for (int i = 1; i <= m; i++) {
13 for (int j = 1; j <= n; j++) {
14 if (p[j - 1] == '*') {
15 dp[i][j] = dp[i][j - 2] || (
16 (p[j - 2] == '.' || p[j - 2] == s[i - 1]) && dp[i - 1][j]
17 );
18 } else if (p[j - 1] == '.' || p[j - 1] == s[i - 1]) {
19 dp[i][j] = dp[i - 1][j - 1];
20 }
21 }
22 }
23
24 return dp[m][n];
25 }
26};Time and space complexity
O(m × n)
Each of the (m + 1) × (n + 1) cells is computed once in constant time.
O(m × n)
The full boolean table is stored. Two rows are enough if memory matters.
Other approaches
Plain recursion (time Exponential in the worst case, space O(m + n) recursion depth)
Match the first character, and on a * either skip the starred element or consume one character and recurse. It is short but exponential on adversarial patterns.
Top-down memoization (time O(m × n), space O(m × n))
The same recursion with a cache on (i, j) indices. It computes only the states that are actually reached and has the same worst case as the table.
Common mistakes
- Forgetting to initialize row 0 for starred patterns. Without it,
s = ""andp = "a*"returns false. - Treating
*as matching any sequence, like a shell glob. Here it repeats only the single element right before it. - In the one-or-more branch, using
dp[i-1][j-2]instead ofdp[i-1][j]. Staying on columnjis what allows the star to absorb more than one character. - Checking
p[j-2]againsts[i-1]without first confirmingp[j-1]is*, which reads the wrong character and can index out of range.
Frequently asked questions
How does * work in regular expression matching?
It applies to the character just before it, so a* means zero or more as and .* means zero or more of any character. The DP handles it with two cases: skip the pair, or consume one matching character and stay on the pair.
What is the time complexity of regular expression matching?
O(m × n) with dynamic programming, where m and n are the lengths of the string and pattern. Naive recursion without memoization can be exponential.
Why is dp[0][j] true for some patterns?
An empty string can match a pattern if every element is followed by * and is used zero times, as in a*b*c*. Row 0 captures exactly those cases.
What is the difference from wildcard matching?
In wildcard matching, * matches any sequence by itself. Here * must follow an element and only repeats that element, which changes the recurrence.