10. Regular Expression Matching¶
Difficulty: Hard
LeetCode Problem View on GitHub
10. Regular Expression Matching
Hard
Given an input string s and a pattern p, 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).
Example 1:
Input: s = "aa", p = "a" Output: false Explanation: "a" does not match the entire string "aa".
Example 2:
Input: s = "aa", p = "a*" Output: true Explanation: '*' means zero or more of the preceding element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input: s = "ab", p = ".*" Output: true Explanation: ".*" means "zero or more (*) of any character (.)".
Constraints:
1 <= s.length <= 201 <= p.length <= 20scontains only lowercase English letters.pcontains only lowercase English letters,'.', and'*'.- It is guaranteed for each appearance of the character
'*', there will be a previous valid character to match.
Solution¶
class Solution {
public boolean isMatch(final String s, final String p) {
return solve(s, p, 0, 0, new Boolean[s.length()][p.length()]);
}
private boolean solve(String s, String p, final int i, final int j, final Boolean[][] dp) {
if(i >= s.length() && j >= p.length()) return true;
if(j >= p.length()) return false;
if(i < s.length() && dp[i][j] != null) return dp[i][j];
final boolean op1 = i < s.length() && (s.charAt(i) == p.charAt(j) || p.charAt(j) == '.');
if(j + 1 < p.length() && p.charAt(j + 1) == '*') {
final boolean op2 = solve(s, p, i, j + 2, dp) || (op1 && solve(s, p, i + 1, j, dp));
if(i < s.length()) dp[i][j] = op2;
return op2;
}
if(op1) return dp[i][j] = solve(s, p , i + 1, j + 1, dp);
if(i < s.length()) dp[i][j] = false;
return false;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here