HDProblem-2203亲和数(KMP算法)

 1 #include<stdio.h>
 2 #include<string.h>
 3 #include<stdlib.h>
 4 #define N 100005
 5 char s1[2*N],s2[N];
 6 int next[N],l1,l2;
 7 
 8 void get_next(char *str,int len)
 9 {
10     int i=-1,j=0;
11     next[0]=-1;            //注意给next[0]赋初值
12     len=strlen(str);
13     if(j<len)
14     {
15         if(i==-1||str[i]==str[j])
16         {
17             i++;
18             j++;
19             if(str[i]!=str[j])        //考虑当i=-1的情况
20                 next[j]=i;
21             else
22                 next[i]=next[j];
23         }
24         else
25             i=next[i];
26     }
27 }
28 void KMP(char *str1,char *str2)
29 {
30     int i=0,j=0,len1,len2;
31     len1=strlen(str1);
32     len2=strlen(str2);
33     while(i<len1&&j<len2)
34     {
35         if(j==-1||str1[i]==str2[j])
36         {
37             i++;
38             j++;
39         }
40         else
41             j=next[j];
42     }
43     if(j>=len2)
44         printf("yes
");
45     else
46         printf("no
");
47 }
48 
49 main()
50 {
51     int i;
52     while(scanf("%s",s1)!=EOF)
53     {
54         l1=strlen(s1);
55         for(i=0;i<l1;i++)
56             s1[l1+i]=s1[i];
57         scanf("%s",s2);
58         l2=strlen(s2);
59         get_next(s2,l2);    //没有返回值的函数用void定义
60         KMP(s1,s2);
61     }
62 }
63 
64 
65     

 可以看看这个链接(http://www.cnblogs.com/dolphin0520/archive/2011/08/24/2151846.html),对于KMP算法的解释直观明了

原文地址:https://www.cnblogs.com/len950717/p/3876614.html