Problem overview
The method isMatch receives a string s and a pattern p. It returns True if the pattern matches all of s, and False otherwise. The pattern holds lowercase letters, dots and stars:
- A letter matches that same letter.
- A dot (
.) matches any one letter. - A star (
*) always comes right after a letter or a dot and repeats it zero or more times. Sob*matches"","b","bb"and so on, and.*matches any string, even an empty one.
The pattern must match the whole of s: matching only a part is not enough. Both strings can be empty, and each has at most 1,000 characters.
For s = "moon" and p = "mo*n" the result is True: m matches m, o* matches both os, and n matches n. For "seat" and "s.a" the result is False: the dot matches the e and a matches a, but the t is left over. For "abc" and "x*a.*" the result is True: x* matches zero xs, a matches a, and .* matches "bc".
The statement asks for O(m · n) time, where m and n are the lengths of s and p.
Approach: does s from index i match p from index j?
The obvious recursive search tries every way a star could match: zero letters, one letter, two letters, and so on. The same question comes back again and again, because different choices for earlier stars can leave you at the same place in both strings. With p = "a*a*a*a*b" and a string of as, the work grows quickly with the length, and every extra star in the pattern multiplies it.
The fix is to name the repeated question: does s from index i match p from index j? Store each answer in a table, dp[i][j], so it is worked out once. There are (m + 1) × (n + 1) such questions, and each one is answered from a few other cells in constant time.
The base case is dp[m][n]: an empty rest of s matches an empty rest of p. For any other cell, first ask whether p[j] matches s[i]: it does if i is inside s and p[j] is the same letter or a dot. Then look at the next pattern character:
- It is a star. The pair
p[j] p[j + 1]can match nothing, which leavesdp[i][j + 2]. Or, if the first letter matches, it can matchs[i]and stay available for more letters, which leavesdp[i + 1][j]. Either one is enough. - It is not a star.
p[j]must matchs[i], and the rest must match too:dp[i + 1][j + 1].
Every cell reads cells below it or to its right, so the table is filled from the end. The answer is dp[0][0].
Step by step
- Store the lengths in
m = len(s)andn = len(p). - Create the table.
dphasm + 1rows ofn + 1values, allFalse. The extra row and column stand for an empty rest. A list comprehension makes a separate row for eachi. - Set
dp[m][n] = True. The rest of columnnstaysFalse, because an empty pattern can't match letters. - Loop over
ifrommdown to 0 withrange(m, -1, -1). Rowmmust be filled too, because a pattern likea*can match an empty rest. - Loop over
jfromn - 1down to 0. Columnnis already set. - Compute
firstMatch:i < m and (p[j] == s[i] or p[j] == '.'). The testi < mcomes first so thats[i]is never read whensis used up. - Handle a star. Check
j + 1 < nbefore readingp[j + 1]. If it is a star,dp[i][j]isdp[i][j + 2] or (firstMatch and dp[i + 1][j]). - Handle a plain character. Otherwise,
dp[i][j]isfirstMatch and dp[i + 1][j + 1]. - Return
dp[0][0], the answer for all ofsand all ofp.
The solution in Python
class Solution:
def isMatch(self, s: str, p: str) -> bool:
m = len(s)
n = len(p)
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[m][n] = True
for i in range(m, -1, -1):
for j in range(n - 1, -1, -1):
firstMatch = i < m and (p[j] == s[i] or p[j] == '.')
if j + 1 < n and p[j + 1] == '*':
dp[i][j] = dp[i][j + 2] or (firstMatch and dp[i + 1][j])
else:
dp[i][j] = firstMatch and dp[i + 1][j + 1]
return dp[0][0]
Python details worth noting:
- A list comprehension for the rows.
[[False] * (n + 1) for _ in range(m + 1)]builds a new inner list for every row. Writing[[False] * (n + 1)] * (m + 1)would repeat one inner listm + 1times, and setting one cell would change the same column in every row. andandorshort-circuit. Ini < m and (...), the right side is skipped wheni < mis false, sos[i]is never read out of range. Reading"a"[1]raisesIndexError: string index out of range. The same goes forj + 1 < n and p[j + 1] == '*'.firstMatchis a real boolean.i < mand the comparisons are booleans, soandandorgiveTrueorFalsehere, and every cell of the table holds one of the two.range(m, -1, -1)counts down frommto 0. The end value-1is excluded.- Single quotes around
'.'and'*'are the same as double quotes. Python has no separate character type: these are one-letter strings.
The table for "moon" and "mo*n"
Here is the table after the loops finish, with T for True and a dot for False. Rows are positions in s and columns are positions in p; end is the empty rest in each:
m o * n end
m T . . . .
o . T . . .
o . T . . .
n . T . T .
end . . . . T
The cell in the top left, dp[0][0], is True, which is the answer. Reading the column of o* (the second column), rows 1, 2 and 3 are True: "oon", "on" and "n" all match o*n, where the star takes two, one and zero letters.
Why the table beats plain recursion
Counting calls of a plain recursive version of the same rules, for the pattern "a*a*a*a*b" against a string of as that never matches, gives 2,365 calls for 10 letters, 23,275 for 20 and 98,735 for 30. The table for the 30-letter string has 31 × 11 = 341 cells, and each is computed once.
Results
isMatch("moon", "mo*n") = True
isMatch("seat", "s.a") = False
isMatch("abc", "x*a.*") = True
isMatch("", "a*") = True
isMatch("", "") = True
isMatch("a", "") = False
isMatch("", ".") = False
isMatch("aa", "a") = False
isMatch("aa", "a*") = True
isMatch("ab", ".*") = True
isMatch("aab", "c*a*b") = True
isMatch("mississippi", "mis*is*p*.") = False
Complexity
Time: O(m · n). The table has (m + 1) × (n + 1) cells, and each cell is computed once from at most two other cells.
Space: O(m · n). The table is the extra memory. For two strings of 1,000 characters that is about a million entries.
Edge cases and common mistakes
- An empty string against a starred pattern.
isMatch("", "a*")isTrue, because the star matches zero letters. This is why rowmof the table is filled too. - An empty pattern.
isMatch("a", "")isFalse, andisMatch("", "")isTrue. - A dot needs a letter.
isMatch("", ".")isFalse: a dot matches exactly one letter, never nothing.firstMatchisFalsewheni == m. - Leftover letters. The pattern must cover all of
s. In the second example, matchings.aagainst the start of"seat"is not enough. - Treating the star as its own character. A star belongs to the character before it, and the pair is handled together. That is why the star branch looks at
j + 2and why the loop never has to handle a star on its own. - Forgetting the zero case. Without
dp[i][j + 2], patterns likex*a.*fail, becausex*must be allowed to match nothing. - Reading
p[j + 1]without checkingj + 1 < n. At the last pattern character there is no next character, and the index would be out of range.
