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
这里采用动态规划来实现.具体操作是给定初始值,然后增加字符来从原状态变为现在的状态(有两种方式,增加s的字符和增加p的字符).比如:
要"aaaa"和"aaaa*"匹配,我们可以这样匹配
1 增加p的字符达到:
比较s[0...i]和p[0...j-2] -- > "aaaa" 和"aaa"
比较s[i] 和 p[j-1] ---> 'a' 和 'a'
2 增加s的字符达到:
比较s[0..i-1]和p[0...j] ---> "aaa" 和 "aaaa*"
比较s[i]和p[j-1] ---> 'a' 和 'a'
也就是当前的状态可能是增加s的字符达到的,也可能是增加p的字符达到的,要判断当前的状态,需要考虑两种状态改变的结果.
class Solution {
public:
bool isMatch(string s, string p) {
//我们采用动态规划,在原来匹配的基础上新增字符是否匹配来推出结果
int m=s.size();
int n=p.size();
//b[0][0]代表长度为0的s与长度为0的p匹配情况
//b[2][1]代表长度为2的s与长度为1的p匹配情况
bool b[m+1][n+1];
//空字符串直接匹配成功
b[0][0]=true;
for(int i=1;i<=m;i++)
{
//非空s跟空的匹配串都匹配失败
b[i][0]=false;
}
for(int i=1;i<=n;i++)
{
//空的s跟非空匹配串匹配的结果
b[0][i] = i>1 && b[0][i-2] && p[i-1] == '*';
}
for(int i=1;i<=m;i++)
{
for(int j=1;j<=n;j++)
{
//如果当前匹配串的字符不为*
if(p[j-1]!='*')
{
//长度为i的s与长度为j的p的匹配结果取决于原匹配结果以及当前字符匹配结果
b[i][j]=b[i-1][j-1] && (s[i-1]==p[j-1] || p[j-1]=='.');
//如果当前匹配串的字符为*
}else{
//长度为i的s与长度为j的p的匹配结果
b[i][j] = b[i][j-2] || //当前s匹配了0个*号前字符
b[i][j-1] || //当前s匹配了1个*号前字符
b[i-1][j] && i>1 && (s[i-1] == p[j-2] || p[j-2] == '.'); //原s匹配当前匹配串p,这时s要增加字符必须与p[j-2]匹配成功
}
}
}
return b[m][n];
}
};