Regular Expression Matching
Regular Expression Matching is LeetCode 10 (Hard). Given a string s and a pattern p, return whether the pattern matches all of s, not just part of it. The pattern has two special characters:
.matches any one character.*means zero or more copies of the character just before it. Soa*is one unit that matches"","a","aa", and so on, and.*matches any run of characters.
Both strings are at most 20 characters long.
- 1 <= s.length <= 20
- 1 <= p.length <= 20
- s contains only lowercase English letters.
- p contains only lowercase English letters, '.', and '*'.
- Every '*' has a valid character before it.
Intuition
The only hard part is a starred unit like a*: it does not say how many characters to eat. Trying one guess fails, because eating too many can starve the rest of the pattern.
So let a table decide. dp[i][j] answers does the first i characters of s match the first j characters of p? A plain character or . must match the last character of s and leave the rest to dp[i-1][j-1]. A starred unit has two choices, and the cell is true if either works:
- Use it zero times: drop the two pattern characters,
dp[i][j-2]. - Use it once more: if it matches
s[i-1], drop that character but keep the unit,dp[i-1][j].
Two strings are matched left to right, and one token can consume a variable amount of the other. Whenever a choice now affects what is left later, and the same "prefix of one, prefix of the other" situation is reached by many choice paths, a 2D table over the two prefix lengths removes the repeated work.
Approach
Before reading on: why does "aab" match "c*a*b"? Which unit is used zero times, and how many characters does a* take? Then write dp[i][j] for a starred p[j-1] in terms of smaller cells. Aim for O(m · n) time.
Table or memoised recursion
Two loops and no recursion.
- Every cell visible: easy to print and check by hand.
- No stack depth: nothing to overflow.
Match from the front: match(i, j) asks whether s[i:] matches p[j:], trying both star choices and caching each answer.
- Reads like the rules: each branch is one sentence of the definition.
- Lazy: only visits states that a real choice path reaches.
Both answer the same (m + 1) · (n + 1) questions once each. The table is the version traced below.
Start from the empty match
dp[0][0] is true: an empty pattern matches an empty string. Every other cell starts false and is filled from cells above and to the left, so filling rows top to bottom and columns left to right always reads finished cells.
Row 0 still matters
Row i = 0 asks whether a pattern prefix matches the empty string. Only starred units used zero times can do that, so a*b* gives true at columns 2 and 4. The same zero-copies rule fills this row; no special loop is needed.
A letter or a dot
If p[j-1] is not *, the cell is true only when i > 0, p[j-1] equals s[i-1] or is ., and dp[i-1][j-1] is true. Both strings lose their last character and the shorter question is already answered.
A star: zero copies or one more
If p[j-1] is *, its unit is p[j-2]. Zero copies reads dp[i][j-2]. One more copy needs p[j-2] to match s[i-1], then reads dp[i-1][j]: the same column, because the unit may keep eating. Those two cells together cover every count of copies.
Read the corner
dp[m][n] compares the whole string with the whole pattern, which is the answer. A partial match never counts, because only this cell is returned.
Code in Python, C++ and Java
Recursion with a cache
match(i, j) looks at what comes next in the pattern. If the next unit is starred, it either skips the unit (j + 2) or, when the first character matches, eats one character and keeps the unit (i + 1). Without the cache the same (i, j) is solved again on every path that reaches it, which is exponential.
Common pitfalls
Letting a star eat as much as it can
# a* takes every 'a' it sees, then move on
while i < m and p[j] in (s[i], '.'):
i += 1
j += 2dp[i][j] = dp[i][j - 2] or (matches and dp[i - 1][j])
s = "aaa", p = "a*a" should be true, with a* taking two letters and the last a taking one. Greedy a* eats all three, the final a finds nothing, and the answer comes out false. Every count of copies has to stay possible.
Reading the star's unit from the wrong place
more = p[j - 1] in (s[i - 1], '.') and dp[i - 1][j]
more = p[j - 2] in (s[i - 1], '.') and dp[i - 1][j]
p[j - 1] is the * itself, which never equals a letter, so the one-more branch never fires and "aa" against "a*" returns false. The repeated character is the one before the star.
Stopping when the string runs out
if i == len(s):
return j == len(p)if j == len(p):
return i == len(s)An empty rest of s can still match a pattern rest like b*c*, by using each unit zero times. For s = "a", p = "ab*" the wrong base returns false once a is matched, though the answer is true.
Edge cases
a*b*Row 0 of the table carries true across columns 2 and 4, so it matches the empty prefix and any run of a's followed by b's.
.* in the middle, such as a.*bThe unit matches any run of characters, including none, so the table checks every split point between the leading a and the final b.
Complexity
(m + 1) · (n + 1) cells, and each reads at most two others. Each row only reads itself and the row above, so two rows of length n + 1 are enough if memory matters.Regular Expression Matching FAQ
How is this different from wildcard matching?
In Wildcard Matching * stands alone and matches any run of characters, while ? matches one. Here * is attached to the character before it and only repeats that character, so a* cannot match b. That is why this table reads p[j-2] and jumps back two columns, while the wildcard table only looks one column back.
Can Python's re module solve it?
re.fullmatch(p, s) is not None gives the same answer, because . and * mean the same thing there and fullmatch requires the whole string. Interviews expect the table, and the library uses a backtracking engine that can be slow on some patterns.
Why does the one-more choice stay in column j?
After eating one character, the starred unit is still available for the next character, so the pattern position does not move. Staying in the same column is how one cell covers one, two, three or more copies: each step up the column eats one more.