这道题花了功夫,所以把想到的的写下来。
这个要从字符串的屁股开始匹配。
道理很简单,从正面匹配,匹配的方式很多,需要全部枚举,不利于缩小问题规模,举个例子,aac和a*a*a*c,从正面开始匹配,从全部需要枚举的匹配情况中举几个例子:aac匹配a*a*a*c,匹配a*a*a*c,匹配a*a*a*c。从屁股开始匹配的话,则可以以几乎确定的方式缩小问题规模。还是aaa和a*a*a*a,第一次,必然匹配掉末尾的a,于是缩小问题为aa和a*a*a*。
考虑从屁股匹配时字符串s,pattern是p,长度分别为ns,np。
重点考察p,p末尾是普通字符:p[np] != s[ns],则无法匹配,返回false。p[np] == s[ns],则缩小规模为p[1, np-1]和s[1, ns-1]两个子串的匹配。
p末尾是'.',直接缩小规模。
p末尾是'*',这时候假如s = Sx,p = Py*,其中,S,P为s和p的子串,x和y是字符。
如果x != y,那么缩小规模为Sx和P的匹配问题。
否则,可以分为三个子问题:
1,y*匹配s中的零个字符,即缩小规模为:Sx和P。
2,y*匹配s中的一个字符,即:S和P。
3,y*匹配s中的多个字符,此时我们每次规模缩小,只缩小一个字符。即:S和Py*。
代码如下,c++:
class Solution {
public:
bool isMatch(string s, string p) {
return match(s, p, s.length() - 1, p.length() - 1);
}
bool match(const string& s, const string& p, int rs, int rp){
if (rp == -1 && rs == -1){
return true;
}
if (rs < -1 || rp <= -1)
return false;
if (p[rp] == '.'){
return match(s, p, rs - 1, rp - 1);
}
else if (p[rp] == '*'){
if (p[rp - 1] != s[rs] && p[rp - 1] != '.'){
return match(s, p, rs, rp - 2);
}
else{
return match(s, p, rs, rp - 2) || match(s, p, rs - 1, rp - 2) || match(s, p, rs - 1, rp);
}
}
else{
if (p[rp] != s[rs]){
return false;
}
else{
return match(s, p, rs - 1, rp - 1);
}
}
}
};