/* --------- KMP failure function ---------------------- */ #include #include #include int f[100]; void mk_f(char *P) { int i, j, m; m = strlen(P); f[0] = 0; i = 1; j = 0; while ( i < m ) { if ( P[i] == P[j] ) { f[i] = j+1; i++; j++; } else { if ( j == 0 ) { f[i] = 0; i++; } else { j = f[j-1]; } } } } int main(int argc, char **argv) { int i, len; if ( argc <= 1 ) { printf("Usage: %s Pattern\n\n", argv[0]); printf(" Program computes KMP failure function\n\n\n"); exit(1); } mk_f( argv[1] ); len = strlen(argv[1]); for (i = 0; i < len; i++ ) { printf("f(%d) = %d\n", i, f[i]); } }