题目链接
http://poj.org/problem?id=2752
题意
给你一个字符串,对于它的每一个前缀,如果同时是它的后缀的话,那么输出这个前缀的位置。
思路
扩展kmp求一下next数组,然后扫一遍每个位置,如果这个位置的next值(也就是这个位置的后缀和前缀的最大匹配长度)是等于后缀长度的话,也就是说这个位置的后缀同时也是它的前缀的话,那么这个位置就是一个答案。
代码
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
#include<cmath>
#include<map>
#include<algorithm>
#include<string>
#include<string.h>
#include<set>
#include<queue>
#include<stack>
#include<functional>
using std::pair;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> PII;
typedef pair<PII,int> PPI;
typedef pair<ll,int> PLI;
const double PI=acos(-1);
const int maxn = 4e5+10;
const int maxm = 1e6 + 10;
const int mod = 1e9+7;
const int INF = 0x3f3f3f3f;
using namespace std;
int nex[maxn];
void getnext(string t)
{
int j=0,po=1,len=t.length();
nex[0]=len;
while(t[j]==t[j+1]&&j+1<len) j++;
nex[1]=j;
for(int i=2;i<len;i++)
{
if(nex[i-po]+i<nex[po]+po) nex[i]=nex[i-po];
else
{
j=nex[po]+po-i;
if(j<0) j=0;
while(i+j<len&&t[j]==t[j+i]) j++;
nex[i]=j;
po=i;
}
}
}
int main()
{
string s;
while(cin>>s)
{
getnext(s);
int len=s.length();
for(int i=len-1;i>=0;i--)
{
if(nex[i]==len-i) printf("%d ",len-i);
}
printf("\n");
}
}