/* ---------------------------------- KMP alg S.Y. Cheung - 2/7/2011 ---------------------------------- */ import java.util.*; public class KMP { public static int[] KMP_failure_function(String P) { int i, j, m; int f[] = new int[P.length()]; m = P.length(); f[0] = 0; i = 1; j = 0; while ( i < m ) { if ( P.charAt(i) == P.charAt(j) ) { f[i] = j+1; i++; j++; } else { if ( j == 0 ) { f[i] = 0; i++; } else { j = f[j-1]; } } } return(f); } public static int KMP(String T, String P, int[] f) { int i, j, m, n; n = T.length(); m = P.length(); i = 0; j = 0; while ( i < n ) { System.out.println("====================================="); System.out.println("Trying:"); System.out.println(" " + "012345678901234567890"); System.out.println(" " + T); System.out.print(" "); for ( int k = 0; k < i-j; k++) System.out.print(" "); System.out.println(P); System.out.print(" "); for ( int k = 0; k < i-j; k++) System.out.print(" "); System.out.println("0123456789"); System.out.println(); System.out.print(" "); for ( int k = 0; k < i; k++) System.out.print(" "); System.out.println("^"); System.out.print(" "); for ( int k = 0; k < i; k++) System.out.print(" "); System.out.println("|"); System.out.println(); if ( P.charAt(j) == T.charAt(i) ) { if ( j == m-1 ) return( i - (m-1) ); i++; j++; } else { System.out.println(); System.out.println("**** Mismatch"); if ( j == 0 ) { System.out.println("-- First character, slide P 1 position"); i++; } else { j = f[j-1]; System.out.println("-- Reset j = " + j); } System.out.println("===================="); } } return(-1); } public static void main(String[] args) { int i, r; String T, P; Scanner in; int[] f; in = new Scanner( System.in ); System.out.println("Try"); System.out.println("T = tomxatexatomatoxxx"); System.out.println("P = tomato"); System.out.println(); System.out.print("T = "); T = in.nextLine(); System.out.print("P = "); P = in.nextLine(); f = KMP_failure_function(P); for (i = 0; i < P.length(); i++ ) { System.out.println("f("+i+") = " + f[i]); } System.out.println(); System.out.println("Matching...."); System.out.println(); r = KMP(T, P, f); if ( r == -1 ) System.out.print("No match found..."); else { System.out.println("Match found at position " + r); System.out.println(); System.out.println("0123456789012345678901234567890123456789"); System.out.println(T); for (i = 0; i < r; i++ ) System.out.print(" "); System.out.println(P); System.out.println(); } } }