推荐大神解析:点我看大神解析
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
#include <iostream>
#include <queue>
#include <vector>
#define int long long
using namespace std;
const int maxn=1e5+10;
string str;
int p[maxn];//以i为中心的最长回文子串的回文半径
string Manacher(string str){
string ans="$#";
//构造新串
for(int i=0;i<str.size();i++){
ans+=str[i];
ans+="#";
}
int mi,right;//mi是当前最长回文串中心,right为最长回文串能够到达的边界
int maxLen=0,maxPoint=0;//最长字串长度,maxPoint为中心点
memset(p,0,sizeof(p));
for(int i=1;i<ans.size();i++){
p[i]=right>i?min(p[2*mi-1],right-i):1;
while(ans[i+p[i]]==ans[i-p[i]])
++p[i];
if(right<i+p[i]){//超过之前的最右端,则改变中心点和对应的最右端
right=p[i]+i;
mi=i;
}
if(maxLen<p[i]){
maxLen=p[i];
maxPoint=i;
}
}
return str.substr((maxPoint-maxLen)/2,maxLen-1);
}
signed main(){
cin>>str;
cout<<Manacher(str)<<endl;
}