sagelearnai

Regular Expression Matching

Difficulty: Hard · Pattern: 2-D Dynamic Programming · LeetCode #10

Implement regex matching with . (any single character) and * (zero or more of the preceding element). The match must cover the entire string s.

Examples

text
s = "aa", p = "a"     →  false
s = "aa", p = "a*"    →  true
s = "ab", p = ".*"    →  true
s = "aab", p = "c*a*b"  →  true   (c* matches zero c's)
s = "mississippi", p = "mis*is*p*."  →  false

Hints

  1. dp[i][j] = whether s[:i] matches p[:j].
  2. A * at p[j−1] pairs with p[j−2]. Either use the pair zero times (dp[i][j−2]), or, if p[j−2] matches s[i−1], use it one more time (dp[i−1][j]).

Approach

text
dp[0][0] = True
dp[0][j] = p[j-1] == '*' and dp[0][j-2]           # patterns like a*b*c* match ""
for i ≥ 1, j ≥ 1:
  if p[j-1] == '*':
      dp[i][j] = dp[i][j-2]                                   # zero copies
              or (match(s[i-1], p[j-2]) and dp[i-1][j])        # one more copy
  else:
      dp[i][j] = match(s[i-1], p[j-1]) and dp[i-1][j-1]
match(c, q) = q == '.' or q == c

Note dp[i−1][j] rather than dp[i−1][j−2]. The x* stays available to absorb more characters, which is how "zero or more" gets encoded. O(m·n) time. Wildcard Matching (LC 44) is the sibling problem, where * stands alone.

Complexity

Time: O(m·n). Space: O(m·n).

Python solution
def isMatch(s, p):
    m, n = len(s), len(p)
    dp = [[False] * (n + 1) for _ in range(m + 1)]
    dp[0][0] = True
    for j in range(2, n + 1):
        dp[0][j] = p[j - 1] == '*' and 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] in (s[i - 1], '.') and dp[i - 1][j])
            else:
                dp[i][j] = p[j - 1] in (s[i - 1], '.') and dp[i - 1][j - 1]
    return dp[m][n]
JavaScript solution
function isMatch(s, p) {
  // Top-down memoized recursion on (i, j).
  const memo = new Map();
  const go = (i, j) => {
    const key = i * 100 + j;
    if (memo.has(key)) return memo.get(key);
    let res;
    if (j === p.length) res = i === s.length;
    else {
      const first = i < s.length && (p[j] === '.' || p[j] === s[i]);
      if (j + 1 < p.length && p[j + 1] === '*') res = go(i, j + 2) || (first && go(i + 1, j));
      else res = first && go(i + 1, j + 1);
    }
    memo.set(key, res);
    return res;
  };
  return go(0, 0);
}