百度的一个图文介绍http://www.sohu.com/a/336648975_453160
package Algorithm.kmp;import java.util.Arrays;public class KMPViolenceMatch {public static void main(String[] args) {String str1 = "BBC ABCDAB ABCDABCDABDE";String str2 = "ABCDABD";int [] next = kmpNext(str2);int kmpsearch = kmpsearch(str1, str2, next);System.out.println("next[] = " + Arrays.toString(next));System.out.println("index = " + kmpsearch);}public static int kmpsearch(String str1, String str2,int [] next){//遍历str1,i指向str1,j指向str2for (int i = 0, j = 0; i < str1.length(); i++) {//str1.charAt(i) != str2.charAt(j),调整j大小//回到匹配表的值相同的下一位while (j > 0 && str1.charAt(i) != str2.charAt(j)){j = next[j - 1];}if (str1.charAt(i) == str2.charAt(j)){j++;}if (j == str2.length()){return i - j + 1;}}return -1;}//获取到一个字符串(子串)的部分匹配值表public static int[] kmpNext(String dest){//创建一个next数组保存部分匹配值int [] next = new int[dest.length()];//如果只有一个字符的话那么next[0] = 0;next[0] = 0;for (int i = 1, j = 0; i < dest.length(); i++) {//dest.charAt(i) != dest.charAt(j),我们需要从next[j-1]获取新的j//直到我们发现有dest.charAt(i) == dest.charAt(j)退出//就是回溯到与下一个匹配值相同的位置,一直没有就是回溯到j = 0while (j > 0 && dest.charAt(i) != dest.charAt(j)){j = next[j-1];}//这是dest.charAt(i) == dest.charAt(j)时//这个条件满足时,部分匹配值就+1if (dest.charAt(i) == dest.charAt(j)){j++;}next[i] = j;}return next;}}