Wildcard Matching
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
class Solution {
public:
/*
//递归解法,会TLE。
bool isMatch(string s, string p) {
int sLen=s.size();
int pLen=p.size();
// if (pLen > 30000) return false; // the trick
if(pLen==0)
return sLen==0;
if(p[0]=='*')
{
while(p[0]=='*')
p=p.substr(1);
while(sLen>0)
{
if(isMatch(s,p))
return true;
sLen--;
s=s.substr(1);
}
return isMatch(s,p);
}
else if(p[0]==s[0] || (sLen>0 && p[0]=='?'))
return isMatch(s.substr(1),p.substr(1));
return false;
}
*/
bool isMatch(string s, string p) {
int sLen=s.size();
int pLen=p.size();
int i=0,j=0,pi=0,pj=pLen;
while(i<sLen)
{
if(s[i]==p[j]||p[j]=='?')
{
i++;
j++;
continue;
}
if(p[j]=='*'){
pj=j++;
pi=i;
continue;
}
if(pj<pLen){
j=pj+1;//j是*后面的字符,i从pi开始逐个匹配
i=++pi;
continue;
}
return false;
}
while(p[j]=='*'){
j++;
}
return j==pLen;
}
};