首页 技术 正文
技术 2022年11月14日
0 收藏 348 点赞 4,839 浏览 821 个字

<题目链接>

<转载于>

题目大意:

 给出一个字符串str,求出str中存在多少子串,使得这些子串既是str的前缀,又是str的后缀。从小到大依次输出这些子串的长度。即输出该字符串所有前缀后缀相等的子串的长度。

解题分析:

    POJ 2752  (kmp求所有公共前后缀长度)如左图,假设黑色线来代表字符串str,其长度是len,红色线的长度代表next[len],根据next数组定义易得前缀的next[len]长度的子串和后缀next[len]长度的子串完全相同(也就是两条线所对应的位置)。我们再求出next[len]位置处的next值,也就是图中蓝线对应的长度。同样可以得到两个蓝线对应的子串肯定完全相同,又由于第二段蓝线属于左侧红线的后缀,所以又能得到它肯定也是整个字符串的后缀。

    所以对于这道题,求出len处的next值,并递归的向下求出所有的next值,得到的就是答案。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;const int M =4e5+;
char s[M];
int nxt[M];
void getnext(){
int i=,j=-;
nxt[]=-;
while(s[i]){
if(j==-||s[i]==s[j]){
nxt[++i]=++j;
}
else j=nxt[j];
}
}
int main(){
while(gets(s)){
getnext();
int len=strlen(s);
int res=len;
int cnt=,output[M];
while(nxt[res]>){ //按上面分析的方式转移
output[++cnt]=nxt[res];
res=nxt[res];
}
sort(output+,output++cnt);
for(int i=;i<=cnt;i++){
printf("%d ",output[i]);
}
printf("%d\n",len);
}
return ;
}

2018-08-06

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,149
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,619
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,462
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,237
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,872
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,040