Regular Expression Matching
Problem Description
Given an input string s and a pattern p, implement regular expression matching with support for '.' and '*' where:
Examples
Input: s = "aa", p = "a"
Output: false
Input: s = "aa", p = "a*"
Output: true
Input: s = "ab", p = ".*"
Output: true
Constraints
1 <= s.length <= 20
1 <= p.length <= 30
s contains only lowercase English letters.
p contains only lowercase English letters, '.', and '*'.
Approach to Solve
Use dynamic programming to match the input string with the pattern.
Code Implementation
class Solution:
def isMatch(self, s: str, p: str) -> bool:
m, n = len(s), len(p)
dp = [[False] * (n + 1) for _ in range(m + 1)]
dp[0][0] = True
for j in range(1, n + 1):
if p[j-1] == '*':
dp[0][j] = dp[0][j-2]
for i in range(1, m + 1):
for j in range(1, n + 1):
if p[j-1] == '.' or p[j-1] == s[i-1]:
dp[i][j] = dp[i-1][j-1]
elif p[j-1] == '*':
dp[i][j] = dp[i][j-2] or (dp[i-1][j] and (p[j-2] == '.' or p[j-2] == s[i-1]))
return dp[m][n]
Explanation
The Regular Expression Matching problem is solved using dynamic programming. Here's a detailed explanation of the approach:
We create a 2D DP table where dp[i][j] represents whether the first i characters of s match the first j characters of p.
Base case: An empty pattern matches an empty string, so dp[0][0] = true.
Handle patterns starting with '': For the first row (empty s), we set dp[0][j] = dp[0][j-2] if p[j-1] is ''. This is because '*' can match zero occurrences of the preceding element.
Fill the DP table:
- If p[j-1] is '.' or matches s[i-1], then dp[i][j] = dp[i-1][j-1].
- If p[j-1] is '*', we have two cases: a) Zero occurrence: dp[i][j] = dp[i][j-2] b) One or more occurrences: dp[i][j] = dp[i-1][j] if p[j-2] is '.' or matches s[i-1]
The final answer is in dp[m][n], where m and n are lengths of s and p respectively.
Time Complexity: O(mn) as we fill each cell in the mn DP table once. Space Complexity: O(m*n) for the DP table.
This approach efficiently handles all cases including '.' (matches any single character) and '*' (matches zero or more of the preceding element), making it a comprehensive solution for regular expression matching.
Complexity
- Time Complexity: O(m*n)
- Space Complexity: O(m*n)