马拉车——最长回文子串长度、回文串个数

题目链接

模板

 

#include<bits/stdc++.h>
using namespace std;
const int maxn=3e5+5;

char s[maxn],str[maxn];
int l1,l2,p[maxn],ans;

void init()
{
    str[0]='$';
    str[1]='#';
    for(int i=0; i<l1; i++)
    {
        str[i*2+2]=s[i];
        str[i*2+3]='#';
    }
    l2=l1*2+2;
    str[l2]='*';
}
int manacher()
{
    int id=0,mx=0,ans=0;
    for(int i=1; i<l2; i++)
    {
        if(mx>i)p[i]=min(p[2*id-i],mx-i);
        else p[i]=1;
        for(; str[i+p[i]]==str[i-p[i]]; p[i]++);
        if(p[i]+i>mx)
        {
            mx=p[i]+i;
            id=i;
        }
        ans=max(ans,p[i]-1);
        //ans+=p[i]/2;  回文串个数
    }
    return ans;
}
int main()
{
    while(~scanf("%s",s))
    {
        l1=strlen(s);
        init();
        printf("%d\n",manacher());
    }
    return 0;
}
View Code

 

posted @ 2019-09-11 19:28  。小姜  阅读(214)  评论(0编辑  收藏  举报