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;
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值