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递归超时,通不过.
注意:
第12行中,循环时,实参 p的值一直没变,s的值一直在加加 -----所以迭代版本中 要保存p的值,++s的值!!!--对应迭代版本中的 25 26 行
(是为了 p中以 ‘ * ’ 后某个位置为起点,s中某个位置为起点 判断匹配失败后 再回到某次++s的位置,从‘ * ’ 后第一位置从头再来---跳过了一些注定无法匹配的起始点 )
bool isMatch(const char *s, const char *p)
{
if (s == NULL || p == NULL) return false;
if (*p == '\0') return *s == '\0';
if (*p == '*')
{
while (*p == '*') ++p;
if(*p=='\0')
return true;
while (*s != '\0')
{
if (isMatch(s, p)) return true; //这里 p的值一直没变,s的值一直在加加-----所以迭代版本中 要保存p的值,++s的值!!!
++s;
}
return isMatch(s, p);
}
else if ((*s != '\0' && *p == '?') || *p == *s)
{
return isMatch(s + 1, p + 1);
}
return false;
}
迭代版本要注意:
找到*的时候,s不要++ 跳过
bool isMatch(const char *s, const char *p)
{
if (s == NULL || p == NULL) return false;
if (*p == '\0') return *s == '\0';
char *backS=NULL;
char *backP=NULL;
while(*s) //循环中s永远不会是结束0,如果p是结束0 那会进行 (3)、(4)判断
{
if (*p == '*') // (1)
{
while (*p == '*') ++p;
if(*p=='\0')
return true;
backS=s;// s当前位置
backP=p;// * 后面第一个位置
// s++;不能s++,如果s++ 那就跳过s中当前字符了,同时也跳过了p中*,只要跳过* 就可以 ,* 当不存在直接跳过,s中当前字符匹配*后第一个
}
else if ( *p == '?' || *p == *s) //(2)
{
s++;
p++;
}
else if(backS) //(3)
{
s=++backS;
p=backP;
}
else // (4) 一种是 从来就没有* ,没有backS ; 一种是 ++backs 导致backs==0 到末尾了
return false;
}
while(*p=='*')
p++;
return (*p=='\0' && *s=='\0');
}