package day01.algorithm.kmp;
public class KMPTest {
public static void main(String[] args) {
String a = "aababcdsujd";
String b = "ababc";
System.out.println(KMP(a, b));
}
public static int[] getNext(String p) {
int[] next = new int[p.length()];
next[0] = -1;
int i = 0;
int j = -1;
while (i < p.length() - 1) {
if (j == -1 || p.charAt(i) == p.charAt(j)) {
i++;
j++;
if (p.charAt(i) == p.charAt(j)) {
next[i] = next[j];
} else {
next[i] = j;
}
} else {
j = next[j];
}
}
return next;
}
public static int KMP(String ts, String ps) {
int[] next = getNext(ps);
int l = ts.length();
int r = ps.length();
int i = 0;
int j = 0;
while (i < l && j < r) {
if (j == -1 || ts.charAt(i) == ps.charAt(j)) {
i++;
j++;
} else {
j = next[j];
}
}
if (j >= r) {
return i - j;
} else {
return -1;
}
}
}