题目地址:https://leetcode.com/problems/regular-expression-matching/
dp问题。题意就是判断正则匹配是否成功
状态多了点
s为需要匹配的字符串,p为模式串。
当p[j]='.'或s[i]=p[j]时,dp[i][j]=dp[i-1][j-1]
如果p[j]='*'有两种情况
如果p[j-1]='.'或p[j-1]=s[i]时,有dp[i][j] = dp[i][j-2] || dp[i][j-1] || dp[i-1][j](分别对应前字符出现0次 1次 多次的情况)
否则 dp[i][j]=dp[i][j-2] //相当于跳过
bool isMatch(string s, string p) {
vector<vector<bool>> dp(s.length()+1, vector<bool>(p.length()+1, false));
dp[0][0] = true;
for (int i = 0; i < p.length(); i++) {
if (p[i] == '*' && dp[0][i-1]) {
dp[0][i+1] = true;
}
}
for (int i = 0; i < s.length(); i++) {
for (int j = 0; j < p.length(); j++) {
if (p[j] == '.') {
dp[i+1][j+1] = dp[i][j];
} else if (p[j] == s[i]) {
dp[i+1][j+1] = dp[i][j];
} else if (p[j] == '*') {
if (p[j-1] != s[i] && p[j-1] != '.') {
dp[i+1][j+1] = dp[i+1][j-1];
} else {
dp[i+1][j+1] = dp[i+1][j] || dp[i][j+1] || dp[i+1][j-1];
}
}
}
}
return dp[s.length()][p.length()];
}