看了一晚上才算看明白,明天继续看
public class KmpSearch {
public static int indexOf(String s, String p) {
if (p.length() == 0) return 0;
int[] next = new int[p.length()];
getNext(p, next);
int i = 0;
int j = 0;
int sLen = s.length();
int pLen = p.length();
while (i < sLen && j < pLen) {
if (j == -1 || s.charAt(i) == p.charAt(j)) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == pLen) {
return i - j;
} else {
return -1;
}
}
private static void getNext(String p, int[] next) {
next[0] = -1;
int j = 0;
int k = -1;
while (j < next.length - 1) {
if (k == -1 || p.charAt(j) == p.charAt(k)) {
j++;
k++;
next[j] = k;
} else {
k = next[k];
}
}
}
public static void main(String[] args) {
int[] next = new int[5];
getNext("ababc", next);
System.out.println(indexOf("ababc","abc"));
}
}