Regular Expression Matching

HardDynamic programmingLeetCode 10 ↗World 5-21
0:00 / 0:00

Match a string against a pattern with . and *. A grid of smaller answers decides each cell: a star can match zero copies or eat one more character.

▼

The problem

LeetCode 10 (Hard). Given a string s and a pattern p, decide whether p matches the whole of s, where . matches any single character and * matches zero or more copies of the element before it.

Examples (LeetCode's): s = "aa", p = "a" → false (an a is left over); s = "aa", p = "a*" → true; s = "ab", p = ".*" → true.

TRY IT ON LEETCODE ▶

The solution

def is_match(s, p):
    m, n = len(s), len(p)
    dp = [[False] * (n + 1) for _ in range(m + 1)]
    dp[m][n] = True
    for j in range(n - 1, -1, -1):
        for i in range(m, -1, -1):
            first = i < m and p[j] in (s[i], '.')
            if j + 1 < n and p[j + 1] == '*':
                dp[i][j] = dp[i][j + 2] or (first and dp[i + 1][j])
            else:
                dp[i][j] = first and dp[i + 1][j + 1]
    return dp[0][0]

Transcript

Regular Expression Matching. You get a string and a pattern. Does the pattern match the whole string? A letter matches itself. A dot matches any single character. A star means zero or more of the character before it.

Take string A A, pattern A: one A is left over, so false. Give the A a star, and it stretches over both: true. String A B, pattern dot star: the dot stretches over anything, so true.

The natural way is recursion. At each star, try two branches: skip it, or, if the first character matches, eat it and keep the star. The same pieces get solved over and over. Twelve A's against eight A stars and a B takes over three hundred thousand calls, for just a hundred and seventeen different questions.

So remember each answer. D P of i, j says whether the string from i matches the pattern from j. First, does character i match pattern j? They must be equal, or the pattern has a dot. If a star follows, skip the pair, or, on a match, eat one character and keep the star. Otherwise, it must match, and both move on.

In code, empty matches empty, so the bottom right is true. Fill from the bottom right, since each cell looks only down or right. The answer is D P of zero, zero.

Let's fill it for string A A B, pattern C star A star B. With an empty pattern, only the empty string matches. Pattern B matches only B. Pattern A star B fails on empty, matches B by skipping the star, A B by eating one A, and A A B by eating two. C never matches, so C star is always skipped, and that column copies its neighbor. The top left is true.

There are M plus one times N plus one cells, each constant work. So the time is order M times N, and so is the space.

Match one, skip the star, or stretch it. That's Regular Expression Matching.