Implement regular expression matching with support for '.'
and '*'
.
'.' Matches any single character. '*' Matches zero or more of the preceding element. The matching should cover the entire>
class Solution { public: bool isMatch(const char *s, const char *p) { int slen = strlen(s), plen = strlen(p), i, j; bool dp[500][500]; memset(dp,false, sizeof(dp)); dp[0][0] = true; for (i = 1; i <= plen; ++i) { if (p[i] == '*') { dp[i][0] = dp[i + 1][0] = dp[i - 1][0]; for (j = 1; j <= slen; ++j) dp[i][j] = dp[i + 1][j] = (dp[i][j - 1] && (p[i - 1] == s[j - 1] || p[i - 1] == '.') || dp[i - 1][j]); ++i; } else for (j = 1; j <= slen; ++j) dp[i][j] = dp[i - 1][j - 1] && (p[i - 1] == s[j - 1] || p[i - 1] == '.'); } return dp[plen][slen]; } };
OR
class Solution {
public:
bool isMatch(const char *s, const char *p) {
const char *ss = s, *sbegin = s, *pbegin = p, *pp = p;
bool dp[500][500];
memset(dp, false, sizeof(dp));
int slen = strlen(s), plen = strlen(p), i, j;
dp[0][0] = true;
for (i = 1; i <= plen; ++i) {
if (p[i - 1] == '*')
dp[i][0] = dp[i - 1][0] = dp[i - 2][0];
for (j = 1; j <= slen; ++j) {
if (p[i - 1] == '*')
dp[i][j] = dp[i - 1][j] = ((dp[i - 2][j - 1] || dp[i][j - 1]) && (p[i - 2] == s[j - 1] || p[i - 2] == '.')) || dp[i - 2][j];
else
dp[i][j] = dp[i - 1][j - 1] && (p[i - 1] == s[j - 1] || p[i - 1] == '.');
}
}
return dp[plen][slen];
}
};
Take notice that
dp[i - 2][j - 1] || dp[i][j - 1]
Can't be written as
dp[i - 2][j - 1]
For exmaple, "aa" and "a*"
recursive:
class Solution { public: bool isMatch(const char *s, const char *p) { if (*p == '\0') return *s == '\0'; if (*(p + 1) == '*') { for (const char *str = s; (*str == *p || *p == '.' && *str); ++str) if(isMatch(str + 1, p + 2)) return true; return isMatch(s, p + 2); } else return (*p == *s || *p == '.' && *s) && isMatch(s + 1, p + 1); } };
Give a wrong code, find out the differences:
class Solution {
public:
bool isMatch(const char *s, const char *p) {
if (*s == *p && *s == '\0')
return true;
if (*(p + 1) == '*') {
for (const char *str = s; *str == *p || *p == '.' || *str == *s; ++str)
if (isMatch(str, p + 2))
return true;
return false;
}
else
return (*p == *s || *p == '.') && isMatch(s + 1, p + 1);
}
};