class Main {
public static void main(String[] args) {
String t = "abcabca";
String s = "aaabbbcdabcabca";
System.out.println(KMP(s,t));
System.out.println("Hello world! - java.jsrun.net ");
}
public static int[] getNext(String t) {
int[] next = new int[t.length()];
next[0] = -1;
int suffix = 0;
int prefix = -1;
while (suffix < t.length() - 1) {
if (prefix == -1 || t.charAt(prefix) == t.charAt(suffix)) {
++prefix;
++suffix;
next[suffix] = prefix;
} else {
prefix = next[prefix];
}
}
return next;
}
public static int KMP(String s, String t) {
int i = 0;
int j = 0;
int[] next = getNext(t);
while (i < s.length() && j < t.length()) {
if (j == -1 || s.charAt(i) == t.charAt(j)) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == t.length()) {
return i - j;
} else {
return -1;
}
}
}