You are on page 1of 2

1.2 C Implementation for KMP #include <stdio.h> #include <stdlib.h> #include <string.

h>

void precompute(char *pattern, int *pre) { int plen = strlen(pattern); int i; memset(pre, 0, sizeof(int)*plen); for (i = 1; i < plen; ++i) { pre[i] = pre[i-1]; while (pattern[i] != pattern[pre[i]]) { if (pre[i] == 0) { pre[i] = -1; break; } else { pre[i] = pre[pre[i]-1]; } } pre[i] = pre[i] + 1; } }

int main(int argc, char **argv) { char *pattern = argv[1]; char *text = argv[2]; int *pre; int m = strlen(pattern); int n = strlen(text); int i, j, overlap;

pre = (int*) malloc((m+1)*sizeof(int)); precompute(pattern, pre); for (i = 0, j = 0; i < n; ) { while (text[i+j] == pattern[j]) { ++j; if (j == m) { printf("found a match at pos: %d\n", i); break; } } if (j > 0) { i += (j - pre[j-1] > 1) ? (j - pre[j-1]):1; j = pre[j-1]; } else { ++i; } } return 0; }

Compile the code using gcc -o kmp kmp.c

You might also like