Title description:
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 (.)”.
Example 4:
Input: s = “aab”, p = “c * a * b”
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches “aab”.
Example 5:
Input: s = “mississippi”, p = “mis * is * p *”
Output: false
Constraints:
0 <= s.length <= 20
0 <= p.length <= 30
s contains only lowercase English letters.
p contains only lowercase English letters, ‘.’, and ’ * '.
It is guaranteed for each appearance of the character ‘*’, there will be a previous valid character to match.
Time complexity: O(nm)
dynamic programming:
State representation: dp[i][j] indicates whether the first i letter of s can match the first j letter of p
State transition:
If p[j] is not a wildcard character '*', Then if and only if s[i] can match p[j] and dp[i-1][j-1] is true, then dp[i][j] is true;
if p[j] is a wildcard '*', there are the following two situations:
- The character s[i] != p[j-1]: In this case, p[j-1]p[j] can be regarded as a null character: dp[i][j] = dp[i][ j-2]
- The character s[i] == p[j-1] or p[j-1] =='.' Assuming p[j-1] is the character a, then:
(1) dp[i][j] = dp[i-1][j] a* can match multiple strings aaaa
(2) dp[i][j] = dp[i][j-1] a* can match a single character a
(3) dp[ i][j] = dp[i][j-2] a* can match empty characters
Note that when initializing dp, because the wildcard character '*' plus its previous character matches a null character, all even-length substrings of p must be initialized first
class Solution {
public boolean isMatch(String s, String p) {
int n = s.length();
int m = p.length();
boolean[][] dp = new boolean[n+1][m+1];
dp[0][0] = true;
for(int j = 1; j < m; j += 2){
dp[0][j+1] = p.charAt(j) == '*' && dp[0][j-1];
}
for(int i = 1; i <= n; i++){
for(int j = 1; j <= m; j++){
if(s.charAt(i-1) == p.charAt(j-1) || p.charAt(j-1) == '.'){
dp[i][j] = dp[i-1][j-1];
}else if(p.charAt(j-1) == '*'){
if(p.charAt(j-2) != s.charAt(i-1) && p.charAt(j-2) != '.'){
dp[i][j] = dp[i][j-2];
}else{
dp[i][j] = (dp[i][j - 2] || dp[i - 1][j - 2] || dp[i - 1][j]);
}
}
}
}
return dp[n][m];
}
}