zoukankan      html  css  js  c++  java
  • KMP算法

    1实现代码

    public class KMP {
    
        public static  int[] KmpNext(String dest){
            //先准备一个Next数组,00000000,默认这个字符串不对称
            int[] next = new int[dest.length()];
            //开始推进Next
            for (int i = 1,j=0; i < dest.length(); i++) {
                while (j>0 && dest.charAt(i) != dest.charAt(j)){
                    j = next[j - 1];
                }
                if (dest.charAt(i) == dest.charAt(j)){
                    j++;
                }
                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++) {
                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 -1;
        }
        
        public static void main(String[] args) {
            String str1 = "abcabcabcd";
            String str2 = "abcabcd";
    
            int []array = KmpNext(str2);
    
            System.out.println( Kmp(str1,str2,array));
    
        }
    }

    2、实现结果

    结果就是 3

  • 相关阅读:
    python3 网络编程
    python3 字典及其方法
    洛谷P2239 螺旋矩阵
    洛谷P4281 紧急会议
    洛谷 P4427 求和
    树的直径
    洛谷P3398 仓鼠找suger
    洛谷P3865 ST表
    洛谷P1638逛画展
    洛谷P1886 滑动窗口
  • 原文地址:https://www.cnblogs.com/karrya/p/11257001.html
Copyright © 2011-2022 走看看