KMP模板

参考:http://www.cnblogs.com/c-cloud/p/3224788.html

 1 #include<stdio.h>
 2 #include<string.h>
 3 void makeNext(const char P[],int next[])
 4 {
 5     int q,k;
 6     int m = strlen(P);
 7     next[0] = 0;
 8     for (q = 1,k = 0; q < m; ++q)
 9     {
10         while(k > 0 && P[q] != P[k])
11             k = next[k-1];
12         if (P[q] == P[k])
13         {
14             k++;
15         }
16         next[q] = k;
17     }
18 }
19 
20 int kmp(const char T[],const char P[],int next[])
21 {
22     int n,m;
23     int i,q;
24     n = strlen(T);
25     m = strlen(P);
26     makeNext(P,next);
27     for (i = 0,q = 0; i < n; ++i)
28     {
29         while(q > 0 && P[q] != T[i])
30             q = next[q-1];
31         if (P[q] == T[i])
32         {
33             q++;
34         }
35         if (q == m)
36         {
37             printf("Pattern occurs with shift:%d
",(i-m+1));
38         }
39     }    
40 }
41 
42 int main()
43 {
44     int i;
45     int next[20]={0};
46     char T[] = "ababxbababcadfdsss";
47     char P[] = "abcdabd";
48     printf("%s
",T);
49     printf("%s
",P );
50     // makeNext(P,next);
51     kmp(T,P,next);
52     for (i = 0; i < strlen(P); ++i)
53     {
54         printf("%d ",next[i]);
55     }
56     printf("
");
57 
58     return 0;
59 }
原文地址:https://www.cnblogs.com/zqy123/p/5993296.html