题目如上
如果用正常递归方法
class Solution { public:
bool isMatch(string s, string p) {
// if(match(s,p)>0)
// {
// return true;
// }
// return false;
s=s+"!";
p=p+"!";
return match(s,p);} bool match (string s,string p) { if(s.length()==1) { // if(p.length()==1||(p.length()==2&&p[0]=='.')||(p.length()==3&&p[1]=='*')) if(p.length()==1) { return true; } else if(p.length()>2&&p[1]=='*') { return match(s,p.substr(2)); } return false; } if(p.length()>2&&p[1]=='*') { if(s[0]==p[0]||p[0]=='.') { return match(s.substr(1),p)|| **// match(s.substr(1),p.substr(2))||** match(s,p.substr(2)); } else return match(s,p.substr(2)); } else if(s[0]==p[0]||p[0]=='.') { return match(s.substr(1),p.substr(1)); } return false; } };
主要注意在这种情况下 对于 第二个char为* 可以省略掉中间的一种情况,因为可以被包含在
另外一种为递归方法
bool isMatch(string s, string p) {
int lens = s.length(), lenp = p.length();
bool ** dp = new bool*[lens + 2];
for (int i = 0; i < lens+2; i++)
dp[i] = new bool[lenp + 2];
for (int i = 0; i < lens+2; i++)
for (int j = 0; j < lenp+2; j++)
dp[i][j] = false;
dp[0][0] = true;
for (int i = 1; i < lenp; i++)
if (p[i] == '*'&&dp[0][i - 1])
dp[0][i + 1] = true;
for (int i = 0; i < lens; i++)
for (int j = 0; j < lenp; j++)
{
if (s[i] == p[j] || p[j] == '.')
dp[i + 1][j + 1] = dp[i][j];
else if (p[j] == '*')
{
if (p[j - 1] != s[i] && p[j - 1] != '.')
dp[i + 1][j + 1] = dp[i + 1][j - 1];
else
dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]);
}
}
return dp[lens][lenp];
}
动态规划的原理是对每一个输入的 string s的位置a,是否有string p的位置b与其进行匹配
这样的话就可以写出状态转移方程,需要注意的是需要先对数组进行处理,其余的没有什么要说的