题目链接
求s中存在多少字串,既是s的前缀 又是s的后缀,输出这些字串的长度
while(l!=0){
sum[k++]=nextt[l];
l=nextt[l];
}
for(int i=k-2;i>=0;i--){
printf("%d ",sum[i]);
}
printf("%d\n",s.length());
代码:
#include "iostream"
#include "algorithm"
#include "cstring"
#include "iomanip"
#include "stdio.h"
#include "stack"
#define maxn 400005
using namespace std;
string s;
int nextt[maxn],sum[maxn];
void getnext(int n){
int i=0,j=-1;
nextt[0]=-1;
while(i<n){
if(j==-1||s[i]==s[j]){
i++;
j++;
nextt[i]=j;
}
else j=nextt[j];
}
}
int main(){
std::ios::sync_with_stdio(false);
while(cin>>s){
memset(nextt,0,sizeof(nextt));
getnext(s.length());
int l=s.length(),k=0;
while(l!=0){
sum[k++]=nextt[l];
l=nextt[l];
}
for(int i=k-2;i>=0;i--){
printf("%d ",sum[i]);
}
printf("%d\n",s.length());
}
return 0;
}