根据判断s串前i个和p串前j个是否匹配来进行动态规划
状态转移方程为match[i][j] =
- match[i-1][j-1] and 当前字符达成匹配
- match[i-1][j] and 当前匹配符为*
- match[i][j-1] and 当前匹配符为*
class Solution {
public:
bool isMatch(string s, string p) {
int slen = s.length(), plen = p.length();
//判断s或p为空字符串
if (slen==0) {
for (int j = 0; j < plen; j ++)
if (p[j] != '*') return false;
return true;
}
if (plen==0) {
return (slen==0);
}
//初始化数组
bool match[slen][plen];
for (int ii=0; ii <slen; ii ++)
for (int jj=0; jj < plen; jj ++)
match[ii][jj] = false;
//初始化match[i][0]和match[0][j]
match[0][0] = (p[0]=='?' || p[0]==s[0]);
if (p[0] == '*') {
for (int i = 0; i < slen; i ++) {
match[i][0] = true;
}
}
if (!match[0][0]) return false;
bool flag = true;
for (int j = 0; j < plen; j ++) {
if (p[j] == '*') match[0][j] = true;
else if (flag) {
if (p[j]=='?' || p[j]==s[0]) {
match[0][j] = true;
flag = false;
} else break;
} else break;
}
//状态转移
for (int i = 1; i < slen; i ++) {
for (int j = 1; j < plen; j ++) {
bool tmp = match[i-1][j-1] && (s[i]==p[j] || p[j]=='?' || p[j]=='*');
match[i][j] = ((match[i-1][j] || match[i][j-1]) && p[j] == '*') || tmp;
}
}
return match[slen-1][plen-1];
}
};