想了一天,一开始太兴奋思路不对。三思而码啊。。
class Solution {
public:
bool isMatch(const char *s, const char *p) {
bool res = true;
int pvalcount = 0;
int i = 0, j = 0;
while (p[i])
{
if (p[i++] != '*')
{
pvalcount++;
}
}
if (pvalcount > strlen(s))
{
return false;
}
i = 0;
while (s[i] && p[j])
{
if (s[i] == p[j] || p[j] == '?')
{
i++; j++;
continue;
}
if (p[j] == '*')
{
while (p[j + 1])
{
if (p[j + 1] == '?')
{
i++; j++;
}
else if (p[j + 1] == '*')
{
j++;
}
else
{
break;
}
}
if (strchr(p + j + 1, '*') == nullptr)
{
int n = strlen(s)-1, m = strlen(p)-1;
while (p[m] != '*')
{
if (p[m] != s[n] && p[m] != '?')
{
return false;
}
m--;
n--;
}
return true;
}
j++;
int stari = i, starj = j;
while (s[stari] && p[starj])
{
if (p[starj] == '*')
{
break;
}
if (s[stari] == p[starj] || p[starj] == '?')
{
stari++;
starj++;
continue;
}
stari = i + 1; starj = j;
i++;
}
if (!s[stari] || !p[starj])
{
i = stari;
j = starj;
break;
}
const char *tmps, *tmpp;
tmps = &s[stari];
tmpp = &p[starj];
return isMatch(tmps, tmpp);
}
return false;
}
if (!s[i])
{
while (p[j] && p[j] == '*')
{
j++;
}
if (p[j])
{
return false;
}
return true;
}
if (!p[j])
{
if (j > 0 && p[j] == '*')
{
return true;
}
return false;
}
return res;
}
};
再给一个一样思路但是简洁得多的版本:
class Solution {
public:
bool isMatch(const char *s, const char *p) {
if (!*p && !*s) return true; // both empty, so sad but true
if (*p == *s) return isMatch(s + 1, p + 1); // match!
else if (*p == '?' && *s) return isMatch(s + 1, p + 1); // weird match!
else if (*p == '*') {
int ret = false;
while (*p == '*') ++p; // I only need just one starlet ;)
if (!*p) return true; // ends with star, the Universe can fit into it now!
while (*s) { // brute force match
const char *ts = s, *tp = p;
while ((*ts == *tp || *tp == '?') && *ts) {
if (*tp == '*') break;
++ts; ++tp;
}
if (!*ts && !*tp) return true; // both empty
// *tp is * then ok, otherwise no exact match :(
if (*tp == '*') {
// we don't need to concern ourself with more exact matches as the * would take care of it,
// and for rest brute force matching will be done
ret |= isMatch(ts, tp);
return ret;
}
if (!*ts) return false; // search exhausted yo! p has more than s can handle :O
++s;
}
return ret;
} else return false; // WAT
}
};