小A的回文串

在这里插入图片描述
主要就是考虑到如何处理,把前导的连续字符放到原字符串末尾
就和处理环状的题类似,字符串开二倍

#include<algorithm>
#include<cstdio>
#include<cmath>
#include<iostream>
#include<cstring>
#include<set>
#include<vector>
#include<string>
using namespace std;

typedef long long ll;
const int N=1e6+10;
const int INF=1000000007;
const double eps=0.0000001;


int Manacher(string s) {
    // Insert '#'
    string t = "$#";
    for (int i = 0; i < s.size(); ++i) {
        t += s[i];
        t += "#";
    }
    // Process t
    vector<int> p(t.size(), 0);
    int mx = 0, id = 0, resLen = 0, resCenter = 0;
    //mx是回文串能延伸到最右端的位置
    //id当前节点回文串的中心点位置
    for (int i = 1; i < t.size(); ++i) {
        p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1;
        while (t[i + p[i]] == t[i - p[i]]) ++p[i];
        //变更中心点
        if (mx < i + p[i]) {
            mx = i + p[i];
            id = i;
        }
        if (resLen < p[i]) {
            resLen = p[i];
            resCenter = i;
        }
    }
    return resLen - 1;//重点
}

int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    string s,str;
    int ans,sum=0;
    cin>>s;
    int len=s.size();
    s=s+s;
    for(int i=0;i+len<s.size();i++)
    {
        str=s.substr(i,len);
        ans=Manacher(str);
        sum=max(ans,sum);
    }

    cout<<sum<<endl;
}


猜你喜欢

转载自blog.csdn.net/weixin_43870114/article/details/89277888