KMP算法

来源:互联网 发布:怎样找淘宝客推广 编辑:程序博客网 时间:2024/05/16 04:33

解题思路已经包含在代码里了


    private int[] getNextArray(char[] chs){             int i;//字符数组的下标指示器             int k;//最大前后缀           int[] next = new int[chs.length];             for(i = 1,k = 0; i < chs.length; i++){                  /**                *   如果 chs[i] == chs[k], 说明最大前后缀相等+1 == next[i],因为前0 ~ k-1与 i-k+1 ~ i-1 是相等的                *   如果 chs[i] != chs[k],那得算出next[k-1]的最大前后缀,而不是与chs[0~k-1]一个个的比,只要比最大相等前缀就好了                */               while(k > 0 && chs[i] != chs[k]){                       k = next[k - 1];                     }               if(chs[i] == chs[k]){                     k++;                 }                 next[i] = k;             }             return next;         }      public boolean kmp(String str1,String str2){          char[] strA = str1.toCharArray();          char[] strB = str2.toCharArray();          int[] next = getNextArray(strB);    //获取需要匹配子串的next数组          int i;  //主串下        int k;  //最大前后缀        for(i = 0,k = 0; i < strA.length; i++){              // 与next同理,只不过上边是自身相比,这次是主串与子串相比            while(k > 0 && strA[i] != strB[k])                  k = next[k-1];              if(strA[i] == strB[k]){                  k++;              }              if(k == strB.length){                  return true;              }          }          return false;      }  
0 0
原创粉丝点击