class Solution {
//1. If the next character of p is NOT '*', then it must match the current character of s.
//Continue pattern matching with the next character of both s and p.
//2. If the next character of p is '*', then we do a brute force exhaustive matching of 0, 1, or
//more repeats of current character of p... Until we could not match any more characters.
//recursion
public:
bool isMatch(const char *s, const char *p) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (*p == '\0') return *s == '\0';
if ( *(p+1) != '*')
return ( (*s == *p) || (*p == '.' && *s != '\0') ) && isMatch(s+1, p+1);
//if *(p+1) is '*', and *s == *p
while ( (*s == *p) || (*p == '.' && *s != '\0') )
{
if( isMatch(s, p+2) ) return true;//pass zero
s++;//pass as more as possible
}
return isMatch(s, p+2);
}
};
second time
class Solution {
//tabulation DP based
public:
bool isMatch(const char *s, const char *p) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int len1 = 0;
for(const char* q = s; *q != '\0' && q != NULL; ++q) len1++;
int len2 = 0;
for(const char* q = p; *q != '\0' && q != NULL; ++q) len2++;
vector<vector<bool> > f(len1+1, vector<bool>(len2+1, false));
f[0][0] = true;
for(int i = 0; i <= len1; ++i)
{
char preChar = '\0';
int preIdx = 0;
for(int j = 1; j <= len2; ++j)
{
if(i >= 1 && (p[j-1] == '.' || s[i-1] == p[j-1])) f[i][j] = f[i-1][j-1];
else if(p[j-1] == '*')
{
if(i >= 1 && (preChar == s[i-1] || preChar == '.')) f[i][j] = f[i-1][j] || f[i][j-1];
f[i][j] = f[i][j] || f[i][preIdx];
//f[i-1][j] = f[i-1][j] || f[i-1][preIdx];
}
if(p[j-1] != '*') preChar = p[j-1], preIdx = j-1;
}
}
return f[len1][len2];
}
};