Regular Expression Matching
Hard
Topics
Given a string s (first line) and a pattern p (second line) supporting . (any single char) and * (zero or more of the preceding element), return true if the pattern matches the entire string.
Example 1
input
pattern
covered by the pattern
The pattern has to account for the whole string.
. stands for one character, and * applies to the token before it, allowing that token any number of times including zero — so a* is one unit, not a wildcard of its own. Here the pattern covers it, so true.Top row is the string; below it the pattern that must account for every character of it.
Input: s = "aa", p = "a*" Output: true
Example 2
input
pattern
covered by the pattern
Input: s = "ab", p = ".*" Output: true
Example 3
input
pattern
not matched
Here the pattern cannot cover it, so
false.Input: s = "mississippi", p = "mis*is*p*." Output: false
Constraints
- 1 <= s.length <= 20
- 1 <= p.length <= 20
- Each * has a valid preceding element.
Editorial — intuition, approach, complexity and pitfalls
Intuition
Let dp[i][j] mean "s[:i] matches p[:j]." A * either drops the preceding element (zero copies) or, if that element matches the current char, consumes one char and stays.
Approach
- Handle empty-string vs patterns like
a*b*in the base row. - For a normal char or ".": dp[i][j] from dp[i-1][j-1] when they match.
- For "*": dp[i][j] = dp[i][j-2] (zero) OR (preceding matches s[i-1] AND dp[i-1][j]).
Dry Run
s = "aa" p = "a*"
dp[i][j] = does s[:i] match p[:j].
dp[0][0] = true. Row 0 is seeded through the stars: p[1] is '*', so
dp[0][2] = dp[0][0] = true, because "a*" matches the empty string by taking zero a's.
"" a *
i=0 "" T F T
i=1 a F T T
i=2 a F F T
i=1 j=1 'a' vs 'a', a literal match dp[1][1] = dp[0][0] = T
i=1 j=2 '*' skip dp[1][0] = F
consume p[0]=='a'==s[0] and dp[0][2] = T -> dp[1][2] = T
i=2 j=1 'a' vs 'a', a literal match dp[2][1] = dp[1][0] = F
i=2 j=2 '*' skip dp[2][0] = F
consume p[0]=='a'==s[1] and dp[1][2] = T -> dp[2][2] = T
answer dp[2][2] = true
The two arms of '*' move in different directions, and that is the part worth
remembering. dp[i][j-2] steps LEFT past the whole x* group, using it zero times.
dp[i-1][j] steps UP one character of s while j stays parked on the same '*', using
it once more. Column j=2 being true on every row is the star absorbing one more 'a'
each time.
It is j-2, not j-1, because '*' and the character it quantifies are a single unit:
skipping the group has to jump two pattern positions. That is also why row 0 is
seeded with a stride of two, and why dp[0][1] stays false -- a bare 'a' cannot
match "".
Note dp[2][1] = false even though s[1] and p[0] are both 'a'. A literal match
inherits from dp[1][0], and "a" is not matched by "", so the only route to a true
answer here runs through the star.Complexity
- Time — O(m*n): fill an (m+1) x (n+1) table.
- Space — O(m*n): the DP table.
Common Pitfalls
- For "*", the zero-copy branch looks back two positions (the char and the star).
Full Solution — all languages
class Solution:
def isMatch(self, s, t):
p=t; m,n=len(s),len(p)
dp=[[False]*(n+1) for _ in range(m+1)]
dp[0][0]=True
for j in range(1,n+1):
if p[j-1]=='*': dp[0][j]=dp[0][j-2]
for i in range(1,m+1):
for j in range(1,n+1):
if p[j-1]=='*':
dp[i][j]=dp[i][j-2] or ((p[j-2]==s[i-1] or p[j-2]=='.') and dp[i-1][j])
elif p[j-1]==s[i-1] or p[j-1]=='.':
dp[i][j]=dp[i-1][j-1]
return dp[m][n]import java.util.*;
class Solution {
public boolean isMatch(String s, String t) {
String p=t;
int m=s.length(),n=p.length();
boolean[][] dp=new boolean[m+1][n+1];
dp[0][0]=true;
for(int j=1;j<=n;j++)if(p.charAt(j-1)=='*')dp[0][j]=dp[0][j-2];
for(int i=1;i<=m;i++)for(int j=1;j<=n;j++) {
if(p.charAt(j-1)=='*')dp[i][j]=dp[i][j-2]||((p.charAt(j-2)==s.charAt(i-1)||p.charAt(j-2)=='.')&&dp[i-1][j]);
else if(p.charAt(j-1)==s.charAt(i-1)||p.charAt(j-1)=='.')dp[i][j]=dp[i-1][j-1];
}
return dp[m][n];
}
}#include <bits/stdc++.h>
using namespace std;
class Solution {
public: bool isMatch(string s, string t) {
string p=t;
int m=s.size(),n=p.size();
vector<vector<char>> dp(m+1,vector<char>(n+1,0));
dp[0][0]=1;
for(int j=1;j<=n;j++)if(p[j-1]=='*')dp[0][j]=dp[0][j-2];
for(int i=1;i<=m;i++)for(int j=1;j<=n;j++) {
if(p[j-1]=='*')dp[i][j]=dp[i][j-2]||((p[j-2]==s[i-1]||p[j-2]=='.')&&dp[i-1][j]);
else if(p[j-1]==s[i-1]||p[j-1]=='.')dp[i][j]=dp[i-1][j-1];
}
return dp[m][n];
}
};/**
* @param {string} s
* @param {string} t
* @return {boolean}
*/ var isMatch = function(s, t) {
const p=t,m=s.length,n=p.length,dp=[];
for(let i=0;i<=m;i++)dp.push(new Array(n+1).fill(false));
dp[0][0]=true;
for(let j=1;j<=n;j++)if(p[j-1]==='*')dp[0][j]=dp[0][j-2];
for(let i=1;i<=m;i++)for(let j=1;j<=n;j++) {
if(p[j-1]==='*')dp[i][j]=dp[i][j-2]||((p[j-2]===s[i-1]||p[j-2]==='.')&&dp[i-1][j]);
else if(p[j-1]===s[i-1]||p[j-1]==='.')dp[i][j]=dp[i-1][j-1];
}
return dp[m][n];
};