Algorithm Day106 - Regular Expression Matching

LC-10 Regular Expression Matching

πŸ“Œ Problem

Implement regular expression matching with support for β€˜.’ and β€˜*’ where:

  • β€˜.’ Matches any single character.
  • β€˜*’ Matches zero or more of the preceding element.

The matching should cover the entire input string (not partial).


πŸ’¬ Examples

Example 1

1
2
Input: s = "aa", p = "a"
Output: false

Example 2

1
2
Input: s = "aa", p = "a*"
Output: true

Example 3

1
2
Input: s = "ab", p = ".*"
Output: true

πŸ’‘ Intuition & Brute Force

A naive recursive solution tries all possibilities for β€˜*’ (match zero, one, multiple). This leads to exponential time in the worst case.

Key observation for DP: define dp[i][j] = whether s[0..i) matches p[0..j). Build up using smaller prefixes.


βœ… Optimized Solution (Dynamic Programming)

Transitions:

  1. If p[j-1] is a normal char or β€˜.’, then:
    dp[i][j] = dp[i-1][j-1] && (p[j-1] == s[i-1] || p[j-1] == β€˜.’)

  2. If p[j-1] == β€˜*’, it stands for zero or more of p[j-2]:

    • Zero occurrence: dp[i][j] = dp[i][j-2]
    • One or more: if p[j-2] matches s[i-1], dp[i][j] = dp[i-1][j]

Initialize dp[0][0] = true, and handle patterns like a*, ab that can match empty string.


πŸ”’ Java Code (DP)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Solution {
public boolean isMatch(String s, String p) {
int m = s.length(), n = p.length();
boolean[][] dp = new boolean[m + 1][n + 1];
dp[0][0] = true;

// Patterns like a*, a*b* can match empty string
for (int j = 2; j <= n; j++) {
if (p.charAt(j - 1) == '*') {
dp[0][j] = dp[0][j - 2];
}
}

for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
char pc = p.charAt(j - 1);
if (pc == '.' || pc == s.charAt(i - 1)) {
dp[i][j] = dp[i - 1][j - 1];
} else if (pc == '*') {
// zero occurrence
dp[i][j] = dp[i][j - 2];
// one or more occurrence
char pprev = p.charAt(j - 2);
if (pprev == '.' || pprev == s.charAt(i - 1)) {
dp[i][j] = dp[i][j] || dp[i - 1][j];
}
}
}
}
return dp[m][n];
}
}

⏱ Complexity Analysis

  • Time: O(m Γ— n) where m = s.length(), n = p.length().
  • Space: O(m Γ— n) for DP table.

✍️ Summary

  • Use DP to avoid exponential recursion.
  • Carefully handle β€˜*’ by considering zero or multiple occurrences.
  • Initialization for empty string vs pattern is important.