1. 程式人生 > >KMP演算法(改進的字串匹配演算法)

KMP演算法(改進的字串匹配演算法)

 /**
     *KMP演算法
     */

    /*
    目標串:ababcabcbababcabacaba
    模式串:ababcabac
      next:001201230

    首先獲取模式串的next陣列,next陣列實際是計算出模式串中重複出現的字元數量,
    每一位的數字n表示從這一位字元之前的n個字元跟整個模式串開始位置相同字元的數量
     */
    public static int[] kmpNext(String dest){
        int[] next=new int[dest.length()];
        next[0]=0;
        //開始推出next
        for(int i=1,j=0;i<dest.length();i++){
            //1 關鍵演算法,當比較到不一致字符時,檢視他的前一位字元的next值,便獲取到跟起始位置相同字元的數量
            //將j移動到那一位再開始比較,如果還不相同則繼續到前一位尋找,知道找到相同字元或者移動到首位
            while(j>0 && dest.charAt(j) != dest.charAt(i)){
                j=next[j-1];
            }
            //2,
            if(dest.charAt(i)==dest.charAt(j)){
                j++;
            }
            //3,
            next[i]=j;
        }
        return next;
    }

    public static int kmp(String str,String dest,int[] next){
        for(int i=0,j=0;i<str.length();i++){
            //類似next陣列演算法,j實際是模式串比較的具體位置,用next陣列可以減少比較不一致時回退比較位置的次數,提升效率
            while(j>0 && str.charAt(i) != dest.charAt(j)){
                j=next[j-1];
            }
            if(str.charAt(i)==dest.charAt(j)){
                j++;
            }
            if(j==dest.length()){//結束
                return i-j+1;
            }
        }
        return 0;
    }