可惜我就是讲不明白 , 直接上书 ,见图片附件 ,手机 500M 像素 蛮清楚的
import java.util.Arrays;
/**
* User: yiminghe
* Date: 2009-2-19
* Time: 16:37:57
*/
public class Kmp {
/**
* index[i] 越小 ,滑动越多,匹配速度越快
*
* @param pattern
* @return
*/
private static int[] getFail(String pattern) {
int[] index = new int[pattern.length()];
index[0] = -1;
int lengthP = pattern.length();
for (int i = 1; i < lengthP; i++) {
int cf = index[i - 1];
while (pattern.charAt(cf + 1) != pattern.charAt(i) && cf >= 0) cf = index[cf];
if (pattern.charAt(cf + 1) == pattern.charAt(i)) index[i] = cf + 1;
else index[i] = -1;
}
return index;
}
public static int kmpFind(String target, String pattern) {
int posP = 0;
int posT = 0;
int lenP = pattern.length();
int lenT = target.length();
int[] index = getFail(pattern);
while (true) {
while (posT < lenT && posP < lenP && target.charAt(posT) == pattern.charAt(posP)) {
++posT;
++posP;
}
if (posP == lenP) {
return posT - lenP;
}
if (posT == lenT) return -1;
if (posP == 0) ++posT;
else
posP = index[posP - 1] + 1;
}
}
public static void main(String[] args) {
//字符串从左开始1
System.out.println(kmpFind("acabaabaabcacaabc", "abaabcac"));
}
}