天天看點

52、正規表達式比對

理清規則然後将規則寫入遞歸即可:

核心:将題目分解為第二個字元是不是'*'這兩種情況。

終止條件: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;
    }
}