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