1 void get_next(char b[], int *next)
2 {
3 int i = 0;
4 int j = -1;
5 next[i] = -1;
6 int len_b = strlen(b);
7 while(i < len_b - 1)
8 {
9 if(j == -1 || b[i] == b[j])
10 {
11 ++i;
12 ++j;
13 next[i] = j;
14 }
15 else
16 {
17 j = next[j];
18 }
19 }
20 }
21
22 int kmp_search(char a[], char b[], int next[])
23 {
24 int i = 0;
25 int j = 0;
26 int len_a = strlen(a);
27 int len_b = strlen(b);
28 while(i < len_a && j < len_b)
29 {
30 if(j == -1 || a[i] == b[j])
31 {
32 ++i;
33 ++j;
34 }
35 else
36 {
37 j = next[j];
38 }
39 }
40 if(j >= len_b)
41 {
42 return i - len_b;
43 }
44 else
45 {
46 return -1;
47 }
48 }