#include <stack>
#include <string>
#include <iostream>
using namespace std;
bool IsMatch(const char *s, const char *p)
{
if (*s == '\0')
{
while(*p != '\0' && *p == '*') ++p;
return (*p == '\0')? true : false;
}
if (*p == '\0') return false;
bool hasAsterisk = false;
while((*p != '\0' && *p != '*') && *s != '\0')
if(*s == *p || *p == '?')
++s, ++p;
else return false;
while(*p != '\0')
{
if (*p == '*')
{
hasAsterisk = true;
++p;
continue;
}
const char * ss = s;
const char * sp = p;
while(*s != '\0' && (*p != '\0' && *p != '*'))
if(*s == *p || *p == '?')
++s, ++p;
else
s = ++ss, p = sp;
if(*s == '\0')return IsMatch(s, p);
}
if (*s != '\0')
{
if (!hasAsterisk)return false;
if (*(--p) == '*') return true;
while(s[1] != '\0') ++s;
while(*p != '*' && (*s == *p || *p == '?'))--s, --p;
return (*p == '*')? true : false;
}
return true;
}
int main(int argc, char** argv)
{
char s[] = "aaabaaabbababaabbabaababbbbbbaabababbbaabaaaabbbba\
bbbbaaaaabaabbbbaaaabbabbaaabbabbbababbaaaabbabbab\
bbbabaabbabbbabbbbabbbbbaabbbababaaaababbbbabababa\
bababbabbbbaaaaababbaaababbabaababbbaaabbbbbababab";
char p[] = "aa*abab*a*a**a*b****ba*ba*aa*****b****b**bbbba*b*b*a**b**b*aab***b*bb***baa*b***a***baa*****a*a*a*ab**a";
cout << (IsMatch(s, p)? "Matched" : "Not Matched") << endl;
s[sizeof(s)-2] = 'a';
cout << (IsMatch(s, p)? "Matched" : "Not Matched") << endl;
return 0;
}