public class Next {
static void getNext(String P, int next[]) {
int j = 0, k = -1;
next[0] = -1;
while (j < P.length() - 1) {
if (k >= 0 && P.charAt(j) != P.charAt(k)) {
k = next[k];
} else {
j++;
k++;
if (P.charAt(j) == P.charAt(k))
next[j] = next[k];
else
next[j] = k;
}
}
}
static int fastFind(String T, String P, int next[]) {
int j = 0, i = 0;
while (j < P.length() && i < T.length())
if (j == -1 || P.charAt(j) == T.charAt(i)) {
j++;
i++;
} else
j = next[j];
if (j < P.length())
return -1;
else
return i - P.length();
}
public static void main(String[] args) {
String T = "aaaaaacdaxue";
String P = "aac";
int[] next = new int[P.length()];
Next.getNext(P, next);
int success = Next.fastFind(T, P, next);
System.out.println(success);
}
}