标签:ext pre java tail [] href tps return class
看了一晚上才算看明白,明天继续看
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"));
}
}
标签:ext pre java tail [] href tps return class
原文地址:https://www.cnblogs.com/acbingo/p/9694550.html