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
递归超时
bool isMatchR(const char *s, const char *p)
{
if(NULL==s && NULL==p)
return true;
if(NULL==s || NULL==p)
return false;
if(*s=='\0' && *p=='\0')
return true;
if(*s=='\0' || *p=='\0')
return false;
if(*p == '*')
{
while(*(p+1)=='*')
++p;
if(*(p+1)=='\0')
return true;
return isMatch(s,p+1) || isMatch(s+1,p);
}
else if(*p == '?')
{
return isMatch(s+1,p+1);
}
else
{
if(*p!=*s)
return false;
return isMatch(s+1,p+1);
}
}
bool isMatchDP(const char *s, const char *p)
{
if(NULL==s && NULL==p)
return true;
if(NULL==s || NULL==p)
return false;
int lens = strlen(s),lenp = strlen(p);
if(lens==0 && lenp==0)
return true;
else if(lens==0 || lenp==0)
return false;
bool** dp = new bool*[lens];
for(int i=0;i=0 && j-1>=0)
dp[i][j] = dp[i-1][j-1];
else
dp[i][j] = false;
}
else
{
dp[i][j] = false;
}
}
}
bool bcode = dp[lens-1][lenp-1];
for(int i=0;i
bool isMatch(const char *s, const char *p)
{
const char* star=NULL;
const char* ss=s;
while(*s)
{
if(*p=='*')
{
star=p;++p;ss=s;
}
else if(*p=='?' || *p==*s)
{
++p;++s;
}
else if(NULL!=star)
{
p=star+1;s=++ss;
}
else
return false;
}
while(*p=='*')
++p;
return !*p;
}
http://tech-wonderland.net/blog/leetcode-wildcard-matching.html
(1) recursive solution or DP, F(i, j) denote if s[0]…s[i-1] and p[0]…p[j-1] is matched or not
F(i, j) = (s[i-1] == p[j-1]) && F(i-1, j-1) if p[j-1] != ‘*’ or ‘?’
F(i, j) = F(i-1, j-1) if p[j] == ‘?’
F(i, j) = OR F(i-l, j-1) for l = 0, … i, if p[j] == ‘*’
(2) greedy: whenever encounter ‘*’ in p, keep record of the current position of ‘*’ in p and the current index in s. Try to match the stuff behind this ‘*’ in p with s, if not matched, just s++ and then try to match again.
http://blog.csdn.net/lifajun90/article/details/10582733