Seek the Name, Seek the Fame

本文解析了POJ2752题目,通过KMP算法求解字符串中前后缀相等的子串长度。介绍了KMP算法next数组的概念,并提供了详细的代码实现。

poj2752:http://poj.org/problem?id=2752

题意:给你一个串,让你求前n个字符和后n个字符相同的n有多少,从小到大输出来。

题解:这一题要深刻理解KMP的next数组,只有深刻理解,才能觉得比较轻松。推荐一个人的博客,这个人讲的比较好。

http://blog.youkuaiyun.com/zhang20072844/article/details/5779452

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<algorithm>
 5 using namespace std;
 6 const int N=400000+5;
 7 int f[N],num[N],top;
 8 char s[N];
 9 int main(){
10    while(~scanf("%s",s)){
11       f[0]=f[1]=0;top=0;
12       int len=strlen(s);
13       for(int i=1;i<len;i++){
14         int j=f[i];
15         while(j&&s[j]!=s[i])j=f[j];
16         f[i+1]=(s[j]==s[i]?j+1:0);
17       }
18       int j=f[len];
19       num[++top]=len;
20       while(j!=0){
21          num[++top]=j;
22          j=f[j];
23       }
24       for(int i=top;i>=1;i--){
25         if(i==top)printf("%d",num[i]);
26         else
27         printf(" %d",num[i]);
28       }
29          printf("\n");
30    }
31 }
View Code

转载于:https://www.cnblogs.com/chujian123/p/3855467.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值