大意:给定一个字符串,求所有可能的既是前缀又是后缀的字串长度。
分析:按题目的意思很像求KMP中的next数组。next[len]是最大的前缀-后缀字符串长度,以此类推next[next[len]]同样为满足条件的前缀-后缀字符串长度。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char str[400005];
int len, next1[400005], ans[400005];
void getnext()
{
int i = 0, j = -1;
next1[0] = -1;
while (i < len)
{
if (j == -1 || str[i] == str[j])
{
i++;
j++;
next1[i] = j;
}
else
j = next1[j];
}
}
int main()
{
while (scanf("%s", str) != EOF)
{
len = strlen(str);
getnext();
ans[0] = len;
int n = 0, i = len;
while (next1[i] > 0)
{
ans[++n] = next1[i];
i = next1[i];
}
for (i = n; i >= 0; i--)
printf("%d ",ans[i]);
printf("\n");
}
return 0;
}