public class KMP {
private static void preKMP(String subcadena, int[] sig) {
int M = subcadena.length();
int j = sig[0] = -1;
for (int i = 1; i < M; i++) {
j++;
if (subcadena.charAt(i) != subcadena.charAt(j)) sig[i] = j;
else sig[i] = sig[j];
while (j >= 0 && subcadena.charAt(i) != subcadena.charAt(j)) {
j = sig[j];
}
}
for (int i = 0; i < M+1; i++)
System.out.format("next[%d] = %d\n", i, sig[i]);
System.out.println();
}
public static void algorithm(String subcadena, String text) {
int M = subcadena.length();
int N = text.length();
int i, j;
int[] next = new int[M+1];
preKMP(subcadena, next);
for (i = 0, j = 0; i < N && j < M; i++) {
while (j >= 0 && text.charAt(i) != subcadena.charAt(j)) {
j = next[j];
}
j++;
System.out.format("attempt %d\n", i);
System.out.format("position:");
for (int t = 0; t < i-j+1; t++)
System.out.print(" ");
System.out.format("%d\n", i-j+1);
System.out.format("text: %s\n", text);
System.out.print("pattern: ");
for (int t = 0; t < i-j+1; t++)
System.out.print(" ");
System.out.format("%s\n ", subcadena);
for (int t = 0; t < j-1; t++)
System.out.print(" ");
for (int t = 0; t < i-j+1; t++)
System.out.print(" ");
System.out.print("^\n");
System.out.format("Shift by %d (%d-next[%d])\n\n", j-next[j], j, j); // shift by needs to be fixed
try {
Thread.sleep(1000);
} catch (Exception e) {}
}
if (j == M) {
System.out.format("Found \'%s\' at position %d\n", subcadena, i-M);
return; // found at offset i
}
// not found
System.out.format("\'%s\' not found\n", subcadena);
}
// test client
public static void main(String[] args) {
String pattern = args[0];
String text = args[1];
KMP.algorithm(pattern, text);
}
}