SDE & MLE Prep

10. Regular Expression Matching

Problem

Implement regular expression matching where . matches any single character and * matches zero or more of the element before it. The pattern must match the entire string s.

Example: s = "aa", p = "a" → false; p = "a*" → true; s = "ab", p = ".*" → true

Constraints: lengths ≤ 20; every * follows a valid character.

dp[i][j] = s[i:] matches p[j:] (suffix form reads naturally). first = i < len(s) and p[j] in {s[i], '.'}. If p[j+1] == '*': skip x* (dp[i][j+2]) or consume one char (first and dp[i+1][j]); else first and dp[i+1][j+1].

Complexity: O(m·n).

class Solution:
    def isMatch(self, s: str, p: str) -> bool:
        @cache
        def dp(i, j):
            if j == len(p):
                return i == len(s)
            first = i < len(s) and p[j] in (s[i], ".")
            if j + 1 < len(p) and p[j + 1] == "*":
                return dp(i, j + 2) or (first and dp(i + 1, j))
            return first and dp(i + 1, j + 1)

        return dp(0, 0)