动规
class Solution {
public:
bool isMatch(const string s, const string p, int i, int j){
if(p[j - 1] == '.') return true;
return s[i - 1] == p[j - 1];
}
bool match(string s, string p) {
int m = s.length(), n = p.length();
bool dp[m + 1][n + 1];
memset(dp, false, sizeof(dp));
dp[0][0] = true;
for(int j = 2; j <= n; j ++){ //i从0开始,因为'a*'这种情况,可以匹配空串
if(p[j - 1] == '*') dp[0][j] = dp[0][j - 2];
}
for(int i = 1; i <= m; i ++){
for(int j = 1; j <= n; j ++){
if(p[j - 1] == '*'){
dp[i][j] |= dp[i][j - 2]; //*匹配0次
if(isMatch(s, p, i, j - 1)) dp[i][j] |= dp[i - 1][j];
}else{
if(isMatch(s, p, i, j)) dp[i][j] |= dp[i - 1][j - 1];
}
}
}
return dp[m][n];
}
}; 
京公网安备 11010502036488号