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 | Input: s = "aa", p = "a" |
Example 2
1 | Input: s = "aa", p = "a*" |
Example 3
1 | Input: s = "ab", p = ".*" |
π‘ 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:
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] == β.β)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 | class Solution { |
β± 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.