Description:
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] represents whether s[0,i-1] and p[0,j-1] is a match.
We can have three situations s[i-1] and p[j-1]:
if p[j] != '.' and [j] != '*'
dp[i][j] = dp[i-1][j-1] + s[i-1] == p[j-1];
else if p[j] == '.'
dp[i][j] = dp[i-1][j-1];
else // p[j] = '*'
if (j>1)
if (dp[i][j-1] || dp[i][j-2])
dp[i][j] = true
else if(i>0 && dp[i-1][j] && (p[j-2]=='.' || s[i-1]==p[j-2] ) ) //(1)
dp[i][j] = true
(1) Because we may have the situation that "" and ".*" is a match, so we need to start i from 0.
<span style="font-size:18px;">public class Solution {
public boolean isMatch(String s, String p) {
if (s == null || p == null)
return false;
int n = s.length();
int m = p.length();
boolean dp[][] = new boolean[n + 1][m + 1];
dp[0][0] = true;
char ch1, ch2;
for (int i = 0; i <= n; i++) {
for (int j = 1; j <= m; j++) {
ch2 = p.charAt(j - 1);
if (ch2 == '*') {
if (j > 1) {
if (dp[i][j - 1] || dp[i][j - 2])
dp[i][j] = true;
else if (i > 0
&& (p.charAt(j - 2) == s.charAt(i - 1) || p
.charAt(j - 2) == '.') && dp[i - 1][j])
dp[i][j] = true;
}
} else if (i > 0) {
ch1 = s.charAt(i - 1);
if (ch2 == '.') {
dp[i][j] = dp[i - 1][j - 1];
} else {
if (ch1 == ch2)
dp[i][j] = dp[i - 1][j - 1];
}
}
}
}
return dp[n][m];
}
}</span>