以下是KMP算法的实现
#include<stdio.h>
2 #include<string.h>3 #include<stdlib.h>
4 #define MAXCHAR 40
5 int next[MAXCHAR];
6
7 int kmp(char * src,char * dest)
8 {
9 int i=0,j=0,m=strlen(src),n=strlen(dest);
10 for(;i<m && j<n;i++,j++)
11 {
12 while(src[i]!=dest[j] &&j!=-1)
13 {
14 j=next[j];
15 }
16 }
17 next[m]=i-j;
18 return j;
19 }
20
21 void kmp_next(char * dest )
22 {
23 int i=0,j=-1,n=strlen(dest),m=0;
24 next[i++]=-1;
25 while(i<n)
26 {
27 if(j==-1 || dest[i]==dest[j])
28 {
29 next[i++]=++j;
30 }else
31 {
32 j=next[j];
33 }
34 printf("%d---%d---%d\n",i,j,next[i]);
35 if(m++ >10)
36 break;
37 }
38
39 for(i=0;i<n;i++)
40 printf("%d---",next[i]);
41 printf("\n");
42
43
44 }
45
46 char * trans(char * src,int x,int y)
47 {
48 int i=x,length='a'-'A';
49 while(i<y)
50 {
51 if(src[i]>='a' && src[i]<='z')
52 src[i]-=length;
53 else if(src[i]>='A' && src[i]<='Z')
54 src[i]+=length;
55 i++;
56 }
57 return src;
58 }
59 void main()
60 {
61 printf("\t\tWelcome to the KMP\nPlease Input a src string:\n");
62 char * src=(char *)calloc(MAXCHAR , sizeof(char));
63 scanf("%s",src);
64 printf("Please Input a dest string:\n");
65 char * dest=(char *)calloc(MAXCHAR , sizeof(char));
66 scanf("%s",dest);
67 kmp_next(dest);
68 int j=kmp(src,dest),m=strlen(src),n=strlen(dest);
69 if(j>=n )
70 printf("%d---%d\nAnd now the result is :%s\n",next[m],j,trans(src,next[ m],next[m]+j));
71 else
72 printf("Sorry!We can't find dest string in the src string!");
73
74 }
以下是KMP算法的实现
#include<stdio.h>
2 #include<string.h>3 #include<stdlib.h>
4 #define MAXCHAR 40
5 int next[MAXCHAR];
6
7 int kmp(char * src,char * dest)
8 {
9 int i=0,j=0,m=strlen(src),n=strlen(dest);
10 for(;i<m && j<n;i++,j++)
11 {
12 while(src[i]!=dest[j] &&j!=-1)
13 {
14 j=next[j];
15 }
16 }
17 next[m]=i-j;
18 return j;
19 }
20
21 void kmp_next(char * dest )
22 {
23 int i=0,j=-1,n=strlen(dest),m=0;
24 next[i++]=-1;
25 while(i<n)
26 {
27 if(j==-1 || dest[i]==dest[j])
28 {
29 next[i++]=++j;
30 }else
31 {
32 j=next[j];
33 }
34 printf("%d---%d---%d\n",i,j,next[i]);
35 if(m++ >10)
36 break;
37 }
38
39 for(i=0;i<n;i++)
40 printf("%d---",next[i]);
41 printf("\n");
42
43
44 }
45
46 char * trans(char * src,int x,int y)
47 {
48 int i=x,length='a'-'A';
49 while(i<y)
50 {
51 if(src[i]>='a' && src[i]<='z')
52 src[i]-=length;
53 else if(src[i]>='A' && src[i]<='Z')
54 src[i]+=length;
55 i++;
56 }
57 return src;
58 }
59 void main()
60 {
61 printf("\t\tWelcome to the KMP\nPlease Input a src string:\n");
62 char * src=(char *)calloc(MAXCHAR , sizeof(char));
63 scanf("%s",src);
64 printf("Please Input a dest string:\n");
65 char * dest=(char *)calloc(MAXCHAR , sizeof(char));
66 scanf("%s",dest);
67 kmp_next(dest);
68 int j=kmp(src,dest),m=strlen(src),n=strlen(dest);
69 if(j>=n )
70 printf("%d---%d\nAnd now the result is :%s\n",next[m],j,trans(src,next[ m],next[m]+j));
71 else
72 printf("Sorry!We can't find dest string in the src string!");
73
74 }