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
class Solution {
public:
bool isMatch(string s, string p) {
return process(s,p,0,0);
}
bool process(string& s,string& p,int si,int pi){
if(pi==p.size())//到结尾了,另一个也必须到结尾
return si==s.size();
//当前匹配下一个字符不是‘*’
if(pi==p.size()-1||p[pi+1]!='*')
return si!=s.size()&&(s[si]==p[pi]||p[pi]=='.')&&process(s,p,si+1,pi+1);
//后一个字符是'*'
while(si!=s.size()&&(p[pi]==s[si]||p[pi]=='.'))
{
if(process(s,p,si,pi+2))
return true;
si++;
}
return process(s,p,si,pi+2);
}
};
动态规划解法:
class Solution {
public:
bool isMatch(string s, string p) {
vector<vector<bool>> dp(s.size()+1,vector<bool>(p.size()+1,false));//建立动归属组
//因为当前的值跟后面的多行和固定的后两列有关,所以需要预先确定最后一行和倒数第1、2列
int sr=s.size();
int pr=p.size();
dp[sr][pr]=true;
for(int i=pr-2;i>=0;i-=2)
{
if(p[i]!='*'&&p[i+1]=='*')
dp[sr][i]=true;
else
break;//遇到一个不行的其他的就都不行
}
//倒数第一列都是false
//倒数第二列,只有sr只剩一个的时候可能相等
if(sr>0&&pr>0)
{
if(s[sr-1]==p[pr-1]||p[pr-1]=='.')
dp[sr-1][pr-1]=true;
}
//下面是正式的一般情况的
for(int i=sr-1;i>=0;i--)
for(int j=pr-2;j>=0;j--)
{
if(p[j+1]!='*')
{
dp[i][j]=(s[i]==p[j]||p[j]=='.')&&dp[i+1][j+1];
}
else
{
int si=i;
while(si!=s.size()&&(p[j]==s[si]||p[j]=='.'))
{
if(dp[si][j+2])
{
dp[i][j]=true;
break;
}
si++;
}
if(dp[i][j]!=true)
dp[i][j]=dp[si][j+2];
}
}
return dp[0][0];
}
};