突然看到這個算法,就在網上找了個寫的不錯的,貼一下:https://www.felix021.com/blog/read.php?2040
然後是hihocoder1032的ac代碼(模板)
代碼:
#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define EPS 1e-7
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long LL;
typedef pair<LL, LL> P;
const int maxn = 1e6 + 5;
const int mod = 1e8 + 7;
char s[maxn], str[maxn*2];
int p[maxn*2];
int manacher()
{
int i;
for(i = 1; s[i]; i++)
str[i*2] = s[i], str[i*2+1] = '#';
str[0] = '?', str[1] = '#', str[i*2] = '\0';
int res = 0, k = 0, maxk = 0;
for(int i = 2; str[i]; i++)
{
p[i] = i < maxk ? min(maxk - i, p[2*k-i]) : 1;
while(str[i-p[i]] == str[i+p[i]]) p[i]++;
if(p[i] + i > maxk)
k = i, maxk = i + p[i];
res = max(res, p[i]);
}
return res - 1;
}
int main (){
int t;
cin>>t;
while (t--){
scanf ("%s",s+1);
cout<<manacher()<<endl;
}
return 0;
}