10. Regular Expression Matching
Implement regular expression matching with support for'.'
and'*'
.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the
entire
input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch("aa","a") → false
isMatch("aa","aa") → true
isMatch("aaa","aa") → false
isMatch("aa", "a*") → true
isMatch("aa", ".*") → true
isMatch("ab", ".*") → true
isMatch("aab", "c*a*b") → true
Solution:
- DP[i][j] means for s from (0,i-1] and p from (0, j-1) matches.
- initialize
- DP[0][0] == true, and other dp[i][0] = false ----> do not need to update
- DP[0][j] = true when string p can be empty ----> XXXXX*
- when p.charAt(j-1) != *
- if(p.charAt(j-1) == s.charAt(j-1) || p.charAt(j-1) =='.') ----> dp[i][j] = dp[i-1][j-1]
- when p.charAt(j-1) == *
- when the character before * != character of s.charAt(i-1) ---> element should be treated as represent 0 times
- p.charAt(j-2)!=s.charAt(i-1) && p.charAt(j-2) != '.'
- dp[i][j] = dp[i][j-2];
- p.charAt(j-2)!=s.charAt(i-1) && p.charAt(j-2) != '.'
- when the character before* == character of s.charAt(i-1) ----> element can be taken as 0 times, 1/more times
- dp[i][j] == dp[i][j-2] || dp[i][j-1] || dp[i-1][j]
- when the character before * != character of s.charAt(i-1) ---> element should be treated as represent 0 times
public boolean isMatch(String s, String p) {
if(s == null || p == null) {
return false;
}
boolean[][] state = new boolean[s.length() + 1][p.length() + 1];
state[0][0] = true;
for (int j = 1; j < state[0].length; j++) {
if (p.charAt(j - 1) == '*') {
if (state[0][j - 1] || (j > 1 && state[0][j - 2])) {
state[0][j] = true;
}
}
}
for (int i = 1; i < state.length; i++) {
for (int j = 1; j < state[0].length; j++) {
if (s.charAt(i - 1) == p.charAt(j - 1) || p.charAt(j - 1) == '.') {
state[i][j] = state[i - 1][j - 1];
}
if (p.charAt(j - 1) == '*') {
if (s.charAt(i - 1) != p.charAt(j - 2) && p.charAt(j - 2) != '.') {
state[i][j] = state[i][j - 2];//0 element
} else {
state[i][j] = state[i - 1][j] || state[i][j - 1] || state[i][j - 2];
}
}
}
}
return state[s.length()][p.length()];
}