题目链接:http://poj.org/problem?id=2752
给定一个字符串s,从小到大输出s中既是前缀又是后缀的子串的长度。
借用KMP算法的next数组,设s的长度为n,则s串本身必定满足条件。其他满足条件的子串都有个特征,就是该子串的最后一个字符肯定与s的最后一个字符相同。这正是next数组发挥作用的时候。从n - 1位既最后一位开始回滚,若s[next[n-1]] == s[n-1],则子串s[0,1,2,...,next[n-1]]是满足条件的子串。然后判断s[next[next[n-1]]] == s[n-1]是否成立,这样一直回滚,直到next[next[.....next[n-1]]] == -1为止。把答案从大到小存下来,再从小到大输出即可。
我们问什么要借用next[n-1]呢? 这是这道题最难想到的, 其实这就是利用了next数组的本质, 我就next数组的时候就有next[n-1]的位置和n-1的位置进行比较来确定公共的前缀和后缀的长度是否增加。 所以这道题的的关键还是要理解next数组的原理, 明白之后就很好理解这道题了。#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
const int maxn = 400000 + 10;
int next[maxn];
int ans[maxn];
char sa[maxn];
void getnext()
{
int n = strlen(sa);
next[0] = -1;
for(int i = 0; i < n; i++)
{
int j = next[i];
while(j!=-1 && sa[i]!=sa[j])
j = next[j];
next[i+1] = j+1;
}
}
int main()
{
while(~scanf("%s", sa))
{
int n = strlen(sa);
getnext();
int top = 0;
ans[top++] = n;
int t = next[n-1];
while(t != -1)
{
if(sa[t] == sa[n-1])
ans[top++] = t+1;
t = next[t];
}
for(int i = top-1; i >= 0; i--)
printf("%d ", ans[i]);
printf("\n");
}
return 0;
}