forked from gzc/CLRS
-
Notifications
You must be signed in to change notification settings - Fork 0
/
KMP.c
56 lines (50 loc) · 900 Bytes
/
KMP.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
* calculate our next array
*/
int* compute_prefix_function(char *pattern)
{
int m = strlen(pattern);
int *next = (int*)malloc(m*sizeof(int));
next[0]=0;
int k = 0;
int q;
for(q = 1;q < m;q++)
{
while(k > 0 && (pattern[k] != pattern[q]) )
k = next[k-1];
if (pattern[k] == pattern[q])
k++;
next[q] = k;
}
return next;
}
int KMP_match(char *text,char *pattern)
{
int n = strlen(text);
int m = strlen(pattern);
int *next = compute_prefix_function(pattern);
int q = 0;
int i;
for(i = 0;i < n;i++)
{
while(q > 0 && (pattern[q] != text[i]) )
q = next[q-1];
if (pattern[q] == text[i])
q++;
if(q == m)
return i+1-m;
}
free(next);
return -1;
}
int main()
{
char *s1 = "bababaababababca";
char *s2 = "ababababca";
int offset = KMP_match(s1,s2);
printf("offset is %d\n",offset);
return 0;
}