字符串-最长回文子串O(n)
#include<stdio.h> #include<string.h> #include<cmath> #include<algorithm> #include<iostream> using namespace std; const int MAXN=110010; char s[2*MAXN];//MAXN太大只能放外面 int p[MAXN*2]; //求给定字符串str的最长回文子串 int solve(char str[]) { s[0]='$'; s[1]='#'; int n=strlen(str); for(int i=0;i<n;++i) { s[2*i+2]=str[i]; s[2*i+3]='#'; } n=n*2+2; s[n]=0; //----------------------------------------- int mx=0,id,ans=1; int mid=0; for(int i=0;i<n;++i) { if(mx>i) p[i]=min(p[2*id-i],mx-i); else p[i]=1; for(;s[i-p[i]]==s[i+p[i]];p[i]++); if(p[i]+i>mx) { mx=p[i]+i; id=i; } if(ans<p[i]) { ans=p[i]; mid=i; } //ans=max(ans,p[i]); } ans--; //if you need the string ~ // mid=mid/2; // int f=mid-ans/2; // int t=mid+ans/2-1; // if(ans%2!=0) f--; // for(int i=f;i<=t;i++) cout<<str[i]; // cout<<endl; return ans; } char str[MAXN]; int main() { while(scanf("%s",str)!=EOF) { int ans=solve(str); cout<<ans<<endl; } return 0; }