题目:
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:
bool isMatch(const char *s, const char *p) {
if (!*s && !*p)
return true;
else if (*p == *s || (*p == '?' && *s))
return isMatch(s + 1, p + 1);
else if (*p == '*') {
bool res = false;
//连续多个*与单个*效果相同
while (*p == '*')
p++;
//若*后面没有字符,则匹配
if (!*p) return true;
while (*s) {
const char *ts = s, *tp = p;
while (*ts && (*ts == *tp || *tp == '?')) {
ts++, tp++;
if (*tp == '*')
break;
}
if (!*ts && !*tp)
return true;
if (*tp == '*')
return isMatch(ts, tp);
if (!*ts) return false;
s++;
}
return false;
}
else
return false;
}
};