问题描述:
Implement wildcard pattern matching with support for ‘?’ and ‘*’.
‘?’ Matches any single character.
‘*’ Matches any sequence of characters (including the empty sequence).
The matching should cover the entire input string (not partial).
The function prototype should be:
bool isMatch(const char *s, const char *p)
Some examples:
isMatch(“aa”,”a”) → false
isMatch(“aa”,”aa”) → true
isMatch(“aaa”,”aa”) → false
isMatch(“aa”, “*”) → true
isMatch(“aa”, “a*”) → true
isMatch(“ab”, “?*”) → true
isMatch(“aab”, “c*a*b”) → false
分析:最开始这道题的思路就是递归,因为我之前做个与此类似的题就是用的递归,但是很不幸,递归会超时。
后来,看到了网上的一些大牛的做法,他们提到用贪心算法(我感觉很奇怪),其实就是把递归用平常的方式实现了一下。通过保留两个临时变量ss,pp,ss是当出现时,s出现的位置,而pp是出现’‘时p的位置。
当第一次出现时,默认代表字符串长度为0,此时,s不变,p+1,当这种方式出错时,检查是否前面出现过,如果出现过,则s=ss+1,且将ss的指针向前挪1,此时,相当于*代表长度为1。依次类推。
代码如下:TLE
bool solve(char *s,int sLength,int sIndex,char *p,int pLength,int pIndex){
if(sLength<=sIndex||pLength<=pIndex){
if(sLength==sIndex&&pLength==pIndex)
return true;
return false;
}
if(p[pIndex]=='?')
return solve(s,sLength,sIndex+1,p,pLength,pIndex+1);
else if(p[pIndex]=='*'){
while(pIndex>0&&pIndex<pLength&&p[pIndex]==p[pIndex-1])
pIndex++;
if(pIndex==pLength)
return true;
for(int i = 0;i<sLength-sIndex+1;i++){
if(solve(s,sLength,sIndex+i,p,pLength,pIndex+1))
return true;
}
return false;
}else{
if(p[pIndex]!=s[sIndex])
return false;
return solve(s,sLength,sIndex+1,p,pLength,pIndex+1);
}
}
bool isMatch(char *s,char *p){
int sLen = strlen(s);
int pLen = strlen(p);
return solve(s,sLen,0,p,pLen,0);
}
代码如下:8ms
bool isMatch(char *s,char *p){
char *ss = NULL;
char *pp = NULL;
while(*s){
if(*p=='?'){s++;p++;}
else if(*p=='*'){ss = s;pp = p++;}
else{
if(*s==*p){s++;p++;}
else{
if(!ss)
return false;
s = ss+1;
ss = s;
p = pp+1;
}
}
}
while(*p=='*')
p++;
return *p=='\0';
}
本文讨论了一个关于字符串匹配的问题,即使用递归方法实现通配符模式匹配遇到了超时问题。通过借鉴贪心算法的思想,作者提出了一个改进的解决方案,并提供了两种实现方式的代码对比,最终通过非递归的方法成功解决了超时问题。

1341

被折叠的 条评论
为什么被折叠?



