码迷,mamicode.com
首页 > 编程语言 > 详细

【模板】KMP算法

时间:2017-04-14 13:42:06      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:log   ==   算法   scan   print   str   logs   src   string   

KMP算法用于字符串匹配

技术分享
 1 /*KMP*/
 2 #include<stdio.h>
 3 #include<string.h>
 4 char s1[1000005],s2[1005];//s1 为待匹配串,s2为模板串
 5 int nxt[1005],n,m;
 6 int main()
 7 {
 8     scanf("%s%s",s1+1,s2+1);
 9     n = strlen(s1+1); m = strlen(s2+1);
10     nxt[1] = 0; int i,k = 0;
11     for(i=2;i<=m;i++)
12     {
13         while(k>0&&s2[k+1]!=s2[i]) k = nxt[k];
14         if(s2[k+1]==s2[i]) k++;
15         nxt[i] = k;
16     }
17     k = 0;
18     for(i=1;i<=n;i++)
19     {
20         while(k>0&&s2[k+1]!=s1[i]) k = nxt[k];
21         if(s2[k+1]==s1[i]) k++;
22         if(k==m) printf("%d\n",i-m+1),k=nxt[k];
23     }
24     for(i=1;i<=m;i++) printf("%d ",nxt[i]);
25     return 0;
26 }
View Code

 

【模板】KMP算法

标签:log   ==   算法   scan   print   str   logs   src   string   

原文地址:http://www.cnblogs.com/hzs2000/p/6708243.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!