首页 > 代码库 > 最长回文子串

最长回文子串

manacher模板题,自己找博客和听同学讲学会了,作者真的很厉害

 

 1 #include<stdio.h>
 2 #include<string.h>
 3 char s1[1000002],s2[2000002];
 4 int n,i,pos,maxr,len[2000002],ans;
 5 int min(int a,int b){return a<b?a:b;}
 6 int max(int a,int b){return a>b?a:b;}
 7 int main(){
 8     while(~scanf("%s",s1+1)){
 9         n=strlen(s1+1);
10         s2[1]=#;
11         pos=1;
12         for(i=1;i<=n;i++){
13             pos++;
14             s2[pos]=s1[i];
15             pos++;
16             s2[pos]=#;
17         }
18         n=pos;
19         pos=0;
20         maxr=0;
21         ans=0;
22         for(i=1;i<=n;i++){
23             if(i<maxr)
24                 len[i]=min(maxr-i,len[2*pos-i]);
25             else
26                 len[i]=1;
27             while(1<=i-len[i]&&i-len[i]<=n&&s2[i-len[i]]==s2[i+len[i]])len[i]++;
28             if(i+len[i]>maxr){
29                 pos=i;
30                 maxr=i+len[i];
31             }
32             ans=max(ans,len[i]-1);
33         }
34         printf("%d\n",ans);
35     }
36 }

 

最长回文子串