POJ-2752 Seek the Name, Seek the Fame
来源:互联网 发布:虚拟linux系统界面 编辑:程序博客网 时间:2024/06/15 22:36
题目链接:poj2752
参考博客:点击打开链接
题目大意:
给你一个字符串S。假如为ababcababababcabab.找出这个字符串中所有的前缀等于后缀的子串。输出它们的长度。
第一个为a,最后一个为b,所以1不行。
前两个为ab,最后二个也为ab,所以2行。
前三个为aba,后三个为bab,所以3不行。
以此类推。。找出全部
当然,全部字符串也是可以的。因为ababcababababcabab和ababcababababcabab肯定是一样的。。。。
解题思路:
这道题也是next数组的一个应用。
既然是求模式串匹配,所以要先求出模式串的next数组。这是第一步。
然后我们开始分析怎么用next数组来完成查找前缀后缀的匹配。
我们还是用上面那个字符串为例子来说明一下。
下标 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
模式串 a b a b c a b a b a b a b c a b a b
next[i] -1 0 0 1 2 0 1 2 3 4 3 4 3 4 5 6 7 8 9
1)当i = len时,next[len] = next[18] = 9,说明整个字符串前9个字符和后9个字符相同,所以9是满足要求的。
2)next[9] = 4,说明在0-8中前4个字符和后4个字符相同。因为由1)得前9个字符和后9个字符相同,所以,S串的0-3等于5-8,而0-3又等于9-12,5-8又等于14-17,所以结果是0-3等于14-17,即4也是满足题意的。
3)next[4]=2,同2,我们可以得到2也是满足题意的。
4)next[2]=0,表明没有相同的前缀和后缀了,这时,就已经找到了这个S串的所有前缀和后缀。
5)结果就是2,4,9,18.
所以,我们可以推得这样的结论:凡是next[i]!=0的,都是模式串的前缀和后缀相同的字符数。
这也是getnext函数的一个重要应用,多理解理解就可以了。
代码如下:
#include <stdio.h>#include <algorithm>#include <iostream>#include <string.h>using namespace std;#define maxn 2000100char s[maxn];int nexts[maxn];int n,m;int a[maxn];void getnexts(){int j=0;int k=-1;nexts[0]=-1;while(j<m){if(k==-1||s[j]==s[k]){j++;k++;nexts[j]=k;}else k=nexts[k];}}int main(){while(~scanf("%s",s)){m=strlen(s);getnexts();int cnt=0;while(nexts[m]!=0){a[cnt++]=m;m=nexts[m];}a[cnt++]=m;for(int i=cnt-1;i>=0;i--)printf("%d%c",a[i],i==0?'\n':' ');} return 0;}
- poj seek the name,seek the fame
- poj---Seek the Name, Seek the Fame
- Seek the Name, Seek the Fame POJ
- Seek the Name, Seek the Fame POJ
- POJ-2752 Seek the Name, Seek the Fame
- poj 2752 Seek the Name, Seek the Fame
- poj 2752 Seek the Name, Seek the Fame(KMP)
- POJ 2752--Seek the Name, Seek the Fame (next)
- POJ:2752Seek the Name, Seek the Fame
- POJ 2752 - Seek the Name, Seek the Fame
- poj 2752 Seek the Name, Seek the Fame
- poj 2752 Seek the Name, Seek the Fame
- POJ-2752-Seek the Name, Seek the Fame
- POJ 2752 Seek the Name, Seek the Fame
- poj 2752 Seek the Name, Seek the Fame
- poj 2752 Seek the Name, Seek the Fame
- POJ 2752 Seek the Name, Seek the Fame
- poj 2752 Seek the Name, Seek the Fame---kmp
- Android中TabActivity使用范例
- MYSQL数据库的基本操作。
- spring MVC 步骤:
- mybatis错误:Invalid bound statement (not found)
- Mr.Smile填坑记——微博、微信debug、release版本切换不能分享
- POJ-2752 Seek the Name, Seek the Fame
- JavaScript定时器原理及高级使用
- gdb多进程/多线程调试实战
- node 回调函数
- HbaseTemplate进阶:利用hbase.properties文件对Hbase的集群和端口进行配置
- 洛谷 P1140 相似基因
- CC26xx SPI
- Windows64 Py-Faster-RCNN的配置
- JSP&Servlet 监听器