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 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", "a*") → true isMatch("aa", ".*") → true isMatch("ab", ".*") → true isMatch("aab", "c*a*b") → true
从左到右扫描模式串,dp[i] 表示s[0- i]是否匹配当前p[0-j] j表示当前匹配的p的下标。
若j= strlen(p) - 1时 dp[strlen(s)] == true与s匹配成功,dp从0下标开始,dp[0]表示空串,初试是i= 0,dp[0]=1,即空串匹配空串。
当p[i + 1] 为常规字符串是,dp[i] = dp[i - 1] && (p[i] == '.' || p[i] == s[j - 1])
当p[i +1] 为‘*’ 时,所有原来为true的下标k及k后面等于*前字符的都为true ,即能匹配p[i]。最后i指向*后面的字符继续匹配!
class Solution {
public:
bool isMatch(const char *s, const char *p) {
if(s == NULL || p == NULL)return false;
// if(!(*s && *p))return false;
int slen = strlen(s);
while(*p == '*')p++;
int plen = strlen(p);
int star_count = 0;
for(int i = 0; p[i]; i++)
{
if(p[i] == '*')star_count++;
}
if(slen < plen - 2 * star_count)return false;
int *dp = new int[slen + 5];
memset(dp, 0, sizeof(int) * (slen + 5));
dp[0] = 1;
for(int i = 0; i < plen; i++)
{
if(p[i + 1] == '*')
{
for(int j = 0; j <= slen; j++)
{
if(!dp[j])continue;
int k;
//dp[j] 为true 则j 和j后面匹配 *之前字母的都 为true
for(k = j + 1; k <= slen && (p[i] == '.' || p[i] == s[k - 1]); k++)
{
dp[k] = 1;
//cout <<i <<"--"<<k<<" "<<dp[k]<<endl;
}
//这里开始逻辑错误,因为循环会j++ 所有j = k - 1,不是j = k
j = k - 1;
}
// dp[0] = dp[0] && dp[i + 1] == '*';
i++;
}
else
{
for(int j = slen; j >= 1; j--)
{
dp[j] = dp[j - 1] && (p[i] == '.' || s[j - 1] == p[i]);
//cout <<i <<"--"<<j<<" "<<dp[j]<<endl;
}
//若p[i]为正常字符,则“”不能匹配p[0 - i]
//dp[0]表示空串对当前的匹配
dp[0] = 0;
}
}
int rtv = dp[slen];
delete[] dp;
return rtv;
}
};