题目描述

请实现一个函数用来匹配包括'.'和'*'的正则表达式。模式中的字符'.'表示任意一个字符,而'*'表示它前面的字符可以出现任意次(包含0次)。 在本题中,匹配是指字符串的所有字符匹配整个模式。例如,字符串"aaa"与模式"a.a"和"ab*ac*a"匹配,但是与"aa.a"和"ab*a"均不匹配

 

 

题目链接:

https://www.nowcoder.com/practice/45327ae22b7b413ea21df13ee7d6429c?tpId=13&&tqId=11205&rp=1&ru=/activity/oj&qru=/ta/coding-interviews/question-ranking

 

 

分析:

每次匹配完,剩下的串匹配都是子问题。

关键点:

1、* 分为三种情况:

*=0,*=1,*=n

可以忽略当前字符,也可匹配1次或n次。

2、结束条件:

字符串匹配完,判断模式串是否匹配完,匹配完true,未匹配完false。

模式串匹配完而字符串未匹配完,返回false。

 

 

public class Solution {
    public boolean match(char[] str, char[] pattern)
    {
        return judge(str,pattern,0,0);
    }
    
    public boolean judge(char[] str,char[] pattern,int s,int p){
        //字符串匹配完
        if(s == str.length){
            //判断模式串当前字符是否可以忽略,*前面的字符可以出现0次
            while(p+1<pattern.length && pattern[p+1] == '*'){
                p+=2;
            }
            //模式串也匹配完,表示可以匹配
            if(p == pattern.length){
                return true;
            }
            //否则表示该情况不可匹配
            return false;
        }
        //字符串未匹配完,而模式串已匹配完,说明不可匹配。
        if(p == pattern.length){
            return false;
        }
        //下一个字符串是 * 的情况。
        if(p+1 < pattern.length && pattern[p+1] == '*'){
            //当前字符相等,或者模式串为 
            if(pattern[p]==str[s] || pattern[p] == '.'){
                //相等三种情况:1、*=0,跳过当前模式串字符 2、*=多次,模式串匹配位置不变 3、*=1,模式串匹配一次
                return judge(str,pattern,s,p+2)||judge(str,pattern,s+1,p)||judge(str,pattern,s+1,p+2);
            }else{
                //不相等情况: *=0,跳过当前模式串字符
                return judge(str,pattern,s,p+2);
            }
        }else if(pattern[p] == '.'){
            return judge(str,pattern,s+1,p+1);
        }else if(pattern[p] == str[s]){
            return judge(str,pattern,s+1,p+1);
        }else{
            return false;
        }
    }
}

 

posted on 2020-06-11 10:52  MoonBeautiful  阅读(138)  评论(0编辑  收藏  举报