在文章里只给出了算法代码以及解释,后边的留下了一份中文一份英文的参考博文地址以便深刻理解KMP算法。ps:中文的亲测,解释原理简单易懂。
<span style="font-size:14px;">A B C A B 0 0 0 1 2</span>
public static int[] next;
public static boolean kmp(String str, String dest) {
for (int i = 0, j = 0; i < str.length(); i ++) {
while (j > 0 && str.charAt(i) != dest.charAt(j))//iterate to find out the right next position
j = next[j - 1];
if (str.charAt(i) == dest.charAt(j))
j ++;
if (j == dest.length())
return true;
}
return false;
}
public static int[] kmpNext(String str) {
int[] next = new int[str.length()];
next[0] = 0;
for (int i = 1, j = 0; i < str.length(); i ++) {//j == 0 means the cursor points to nothing.
//the j here stands for the number of same characters for postfix and prefix, instead of
//the index of the end of prefix.
while (j > 0 && strt.charAt(j) != sr.charAt(i))
j = next[j - 1]; //watch out here! it's j - 1 here, instead of j
if (str.charAt(i) == str.charAt(j))
j ++;
next[i] = j;
}
return next;
}
原文:http://blog.csdn.net/wj512416359/article/details/42081293