题目:字符串匹配。‘.’可以匹配任意字符,‘*’可以匹配任意多个相同的字符。
‘.’ 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
解法:
最简单的想法就是用递归:
1、递归出口:s字符串没结束,p结束了。不匹配。
s字符串结束,p结束。匹配。
s字符串结束,p没结束但是后面都是字母加星号的结构。匹配。
2、递归过程:
如果p[i+1]为‘*’,p可以匹配s任意多个等于p[i]的字符。对一个,两个,...的情况都判断一下,如果有一种情况可以,就返回true,否则返回false。
如果p[i+1]不为“*”,则要p[i]=s[i],并且后面的字符串也要匹配,才返回true。否则返回false。
代码:
class Solution {
public:
bool isMatch(string s, string p) {
return isMatch_(0,0,s,p);
}
bool isMatch_(int i,int j,string& s,string& p)
{
int len1=s.length(),len2=p.length();
if(i!=len1&&j==len2) return false;
if(i==len1&&j==len2) return true;
if(i==len1&&j!=len2)
{
while(j+1<len2&&p[j+1]=='*') j+=2;
if(j==len2) return true;
else return false;
}
if(j+1<len2&&p[j+1]=='*')
{
if(isMatch_(i,j+2,s,p)) return true;
while(i<len1&&(s[i]==p[j]||p[j]=='.'))
{
i++;
if(isMatch_(i,j+2,s,p)) return true;
}
return false;
}
else if(s[i]==p[j]||p[j]=='.')
{
return isMatch_(i+1,j+1,s,p);
}
else return false;
}
};