#include <cstdio>
#include <cstring>
typedef unsigned long long ll;
#define fg(i, j, k, l) for (int i = j; i <= k; i += l)
const int M = 400010;
const ll b = 11;
char c[M];
int len;
ll hh[M] = { 0, b }, a[M];
int main() {
fg(i, 2, 400010, 1) hh[i] = hh[i - 1] * b;
while (scanf("%s", c + 1) != EOF) {
memset(a, 0, sizeof a);
len = strlen(c + 1);
fg(i, 1, len, 1) a[i] = a[i - 1] * b + (ll)(c[i]);
fg(i, 1, len, 1) //暴力枚举,hash出来的前缀是否等于后缀
if (a[i] == a[len] - a[len - i] * hh[i]) printf("%d ", i);
printf("
");
}
return 0;
}
也可以KMP算法实现
#include<cstdio> #include<iostream> #include<cmath> #include<cstring> #define maxn 1000010 using namespace std; char s[maxn]; int n,pre[maxn],list[maxn]; int main(){ scanf("%d",&n); scanf("%s",s+1); for (int i=2,j=0;i<=n;i++){ while (j&&s[j+1]!=s[i]) j=pre[j]; if (s[j+1]==s[i]) j++; pre[i]=j; } for (int i=n;i;i=pre[i])
list[++list[0]]=i; for (int i=list[0];i>=1;i--) printf("%d ",list[i]); printf(" "); return 0; }