解题思路:
(1)递归(超时)
class Solution {
public:
bool helper(const char *s, const char *p) {
if(*s=='\0' && *p=='\0') return true;
else if(*s=='\0' && *p=='*') return helper(s,p+1);
else if(*s=='\0') return false;
if(*s!='\0' && *p=='\0') return false;
else if(*s!='\0' && (*s==*p || *p=='?')) return helper(s+1,p+1);
else if(*s!='\0' && *p=='*') return helper(s,p+1) || helper(s+1,p+1) || helper(s+1,p);
else return false;
return false;
}
bool isMatch(const char *s, const char *p) {
return helper(s,p);
}
};
(2)动态规划
class Solution {
public:
bool isMatch(const char *s, const char *p) {
int m=strlen(s),n=strlen(p);
vector<vector<bool>> v(m+1,vector<bool>(n+1,false));
v[0][0]=true;
for(int i=1;i<n+1;i++) {
if(p[i-1]=='*') v[0][i]=v[0][i-1];
}
for(int i=1;i<m+1;i++) {
for(int j=1;j<n+1;j++) {
if(s[i-1]==p[j-1] || (p[j-1]=='?')) v[i][j]=v[i-1][j-1];
if(p[j-1]=='*') v[i][j]=v[i-1][j]||v[i][j-1]||v[i-1][j-1];
}
}
return v[m][n];
}
};