模式匹配也算是字符串中比较难得题目了吧,动不动就是TLE。
题目一:Regular Expression Matching
Implement rugular expression matching with support for "." and "*". "." matches any single character, "*" matches zero or more of the preceding element.
思路:两个字符串问题。关键看pattern串,“*”没有或者有多个。这道题由于分支不算太多,用递归就可以解决。
class Solution {
public:
bool isMatch(const char *s, const char *p) {
if(*s=='\0' && *p=='\0') return true;
if(*p=='\0') return false;
if(*(p+1)=='*'){
if(*s==*p || *p=='.'&&*s!='\0'){
if(isMatch(s+1, p) || isMatch(s, p+2))
return true;
}
else return isMatch(s, p+2); //舍弃当前这个值
}
else if(*s==*p || *p=='.'&&*s!='\0')
return isMatch(s+1, p+1);
return false;
}
};
第二题: Wildcard Matching
Implement wildcard pattern matching with support for "?" and "*". "?" matches any single character. "*" matches any sequence of characters (including empty sequence). The matching should cover the entire input string (not partial).
思路:这道题最初我还是尝试了递归来接,结果TLE败下阵来了。我再次求助于discuss小伙伴。。通过对一些部分做了优化,将需要递归的情况降到了最低,最终只需要遇到“*”才进行递归。
class Solution {
public:
bool isMatch(const char* s, const char* p, int i, int j){
if(!s[i] && !p[j]) return true;
if(s[i]==p[j] || p[j]=='?' && s[i]!='\0')
return isMatch(s, p, i+1, j+1);
if(p[j]=='*'){
while(p[j]=='*') j++;
if(p[j]=='\0') return true;
while(i<strlen(s)){
int k=i;
int kk=j;
while(k<strlen(s) && (s[k]==p[kk] || p[kk]=='?')){
k++;
kk++;
}
if(!s[k] && !p[kk]) return true;
if(p[kk]=='*') return isMatch(s, p, k, kk);
if(!s[k]) return false;
i++;
}
}
return false;
}
bool isMatch(const char *s, const char *p) {
if(s==NULL || p==NULL) return false;
int m=strlen(s);
int n=strlen(p);
if(m==0 && n==0) return true;
return isMatch(s, p, 0, 0);
}
};
说明:像这种方式优化递归算法大概只有想这样的字符匹配中才存在吧。