一開始採用递归写。TLE。
class Solution {
public:
bool flag;
int n,m;
void dfs(int id0,const char *s,int id1,const char *p){
if(flag)return;
if(id0>=n){
if(id1>=m)flag=1;
else{
int j=0;
while(j<m&&p[j]=='*')j++;
if(j>=m)flag=1;
}
return;
}
else if(id1>=m)return;
if(p[id1]=='?'||p[id1]==s[id0]){
dfs(id0+1,s,id1+1,p);
}
else if(p[id1]=='*'){
for(int j=id0;j<n;++j) dfs(j,s,id1+1,p);
}
}
bool isMatch(const char *s, const char *p) {
for(n=0;s[n];++n);
for(m=0;p[m];++m);
flag=0;
dfs(0,s,0,p);
return flag;
}
};
粗剪枝了,还是超时。
看了下Discuss,发现能够贪心:
class Solution {
public:
bool isMatch(const char *s, const char *p) {
const char*lastp=NULL,*lasts=NULL;
while(*s){
if(*s==*p||*p=='?'){
p++;
s++;
}
else if(*p=='*'){
//不匹配,仅仅记录
lastp=p++;
lasts=s;
}
else if(lastp!=NULL){
p=lastp+1;
s=++lasts;//逐渐递增匹配1个字符、2个字符...
}
else return false;
}
while(*p&&*p=='*')p++;
return *p=='