题意
给你一个字符串 长度4e5以内 然后从小到大(子串长度)输出即是前缀也是后缀的子串的长度
思路
KMP算法能够很好的解决公共前后缀问题 首先 每一个字符串本身一定是最长的符合条件的解 其次
我们可以用next数组中的值来递归的深入得出从大到小的值每一个字符串的最长公共前后缀一定是满足条件的最优解(除本身以外);
所以用 之所以需要t + 1 是因为从零开始嘛 t 刚开始从next[strlen(str) - 1] 开始而不是 next[strlen(str)] 开始是因为本身的这种情况
是被特殊考虑的
代码
#include <cstdio>
#include <cstring>
const int N = 4e5 + 10;
char str[N] ;
int next[N];
int ans[N] , cnt , len;
void Pre_Kmp()
{
int i , j;
i = 0 , j = next[0] = -1, len = strlen(str);
while (i < len) {
while (j != -1 && str[i] != str[j]) j = next[j];
next[++i] = ++j;
}
}
int main()
{
while (~scanf("%s",str)) {
Pre_Kmp();
cnt = 0;
int t = next[len - 1];
while (t != -1) {
if (str[t] == str[len - 1]) ans[cnt ++] = t + 1;
t = next[t];
}
for (int i = cnt - 1; i >= 0 ; i --) {
printf("%d ",ans[i]);
}
printf("%d\n",len);
}
}