Regular Expression Matching

Hard

Topics
StringDynamic ProgrammingRecursion

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

inputaa
patterna*
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

inputab
pattern.*
covered by the pattern
Input:  s = "ab", p = ".*"
Output: true

Example 3

inputmississippi
patternmis*is*p*.
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

  1. Handle empty-string vs patterns like a*b* in the base row.
  2. For a normal char or ".": dp[i][j] from dp[i-1][j-1] when they match.
  3. 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]
SensAI
Beta
Tap the mic to stop voice mode