首页 > 技术文章 > 正则匹配

ningxinjie 2020-07-08 08:15 原文

 

 //动态规划

 public boolean match(char[] str, char[] pattern){
        //a.*vc*
        int sLen=str.length,pLen=pattern.length;
        boolean[][] dp=new boolean[sLen+1][pLen+1];
        dp[0][0]=true;
        for(int i=2;i<=pLen;i++){
            dp[0][i]=pattern[i-1]=='*'&&dp[0][i-2];
        }
        char s,p;
        for (int i = 1; i <=sLen; i++) {
            s=str[i-1];
            for (int j = 1; j <=pLen; j++) {
                p=pattern[j-1];
                if(s==p){
                    dp[i][j]=dp[i-1][j-1];
                }
                else {
                    if(p=='.'){
                        dp[i][j]=dp[i-1][j-1];
                    }
                    else if(p=='*'){
                        //a ab*
                        //要么匹配0次,要么匹配多次
                        //如果*前一位和s不相同,则匹配0为
                        //如果相同的话,
                        if(j>=2){
                            char val=pattern[j-2];
                            if(val==s||val=='.'){   //ab ab*    a ab*
                                dp[i][j]=dp[i][j-1]||dp[i-1][j];
                            }
                            dp[i][j]=dp[i][j]||dp[i][j-2];//ab ac*
                        }
                    }
                }
            }
        }
        return dp[sLen][pLen];
    }

//递归

 public boolean match(char[] str, char[] pattern)
    {
           if(str.length==0&&pattern.length==0){
            return true;
        }
        return mathch1(str,0,pattern,0);
    }
      private boolean mathch1(char[] str,int i, char[] pattern,int j){
        if(j==pattern.length){
            return str.length==i;
        }
        boolean first_isMatch=(i!=str.length)&&(str[i]==pattern[j]||pattern[j]=='.');
        //存在下一个 且为*
        if(j<pattern.length-1&&pattern[j+1]=='*'){
            //如果当前不满足,则a*这样直接跳过(0个匹配的情况)
            //如果匹配得上则首字匹配和后面继续匹配(多个匹配的情况)
            return mathch1(str,i,pattern,j+2)||(first_isMatch&&mathch1(str,i+1,pattern,j));
        }else {
            return first_isMatch&&mathch1(str,i+1,pattern,j+1);
        }
    }

 

推荐阅读