• 正则匹配


     //动态规划

     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);
            }
        }
  • 相关阅读:
    SQL2014还原到2008
    SQL SERVER2014 安装 Error code 0x858C001B.
    c++builder XE7 C++11 C++0x 新语法
    c++Builder XE6 MD5 加密算法 BASE64 URL 编码
    手机新功能
    xe fmx 怎么改变button颜色
    XE6 任务栏 控件
    js里面return 和 return false的区别
    web.xml的contextConfigLocation作用及自动加载applicationContext.xml
    mybatis-config.xml配置
  • 原文地址:https://www.cnblogs.com/ningxinjie/p/13264787.html
Copyright © 2020-2023  润新知