理清规则然后将规则写入递归即可:
核心:将题目分解为第二个字符是不是'*'这两种情况。
终止条件:1、str和pattern都同时遍历到最后,返回true。2、str遍历还没结束,pattern就已经遍历完,返回false
不同情形:1、如果pattern的下一个字符是'*',有两种大情况,一种是str当前字符不等于pattern字符,一种是等于(pattern字符为'.'的时候也相当于等于)
对于str等于pattern的情况又有三种操作1⃣️str位置不变,pattern后移两个字符2⃣️str后移一个字符和pattern后移两个字符3⃣️str后移一个字符,pattern位置不变。
2、如果str当前字符等于pattern字符(包括pattern当前字符为'.'的情况),那么同时后移一个字符。
代码如下
public class Solution {
public boolean match(char[] str, char[] pattern)
{
if(str==null||pattern==null){
return false;
}
if(str.length==0){
if(pattern.length==0)
return true;
}
return Macher(str,0,pattern,0);
}
public boolean Macher(char[] str,int indexofstr,char[] pattern,int indexofpattern){
if(indexofstr==str.length&&indexofpattern==pattern.length){
return true;
}
if(indexofstr<str.length&&indexofpattern==pattern.length){
return false;
}
if(indexofpattern<pattern.length-1&&pattern[indexofpattern+1]=='*'){
if((indexofstr<str.length&&str[indexofstr]==pattern[indexofpattern])||
(indexofstr<str.length&&pattern[indexofpattern]=='.')){
return Macher(str,indexofstr,pattern,indexofpattern+2)||
Macher(str,indexofstr+1,pattern,indexofpattern+2)||
Macher(str,indexofstr+1,pattern,indexofpattern);
}
else{
return Macher(str,indexofstr,pattern,indexofpattern+2);
}
}
if(indexofstr<str.length&&(str[indexofstr]==pattern[indexofpattern]||pattern[indexofpattern]=='.')){
return Macher(str,indexofstr+1,pattern,indexofpattern+1);
}
return false;
}
}