最长对称子串(马拉车算法)

版权声明:沃斯里德小浩浩啊 https://blog.csdn.net/Healer66/article/details/83115922

7-1 最长对称子串 (25 分)

对给定的字符串,本题要求你输出最长对称子串的长度。例如,给定Is PAT&TAP symmetric?,最长对称子串为s PAT&TAP s,于是你应该输出11。

输入格式:

输入在一行中给出长度不超过1000的非空字符串。

输出格式:

在一行中输出最长对称子串的长度。

输入样例:

Is PAT&TAP symmetric?

输出样例:

11

不知道暴力能不能过。

马拉车板子题

#include <bits/stdc++.h>
using namespace std;
const int maxn =1e6;
string str;
string temp;
int len[maxn<<1];
int init(string st)
{
    int len = st.size();
    temp="@";
    for(int i =1; i<=2*len; i+=2)
    {
        temp+='#';
        temp+=st[i/2];
    }

    temp+='#';
    temp+='$';
    temp+='\0';
    return 2*len+1;

}
int Manacher(string st,int len_)
{
    int mx = 0,ans = 0,po =0;
    for(int i =1; i <= len_ ; i++)
    {
        if(mx>i)
            len[i]=min(mx-i,len[2*po-i]);
        else
            len[i]=1;
        while(st[i-len[i]]==st[i+len[i]])
            len[i]++;
        if(len[i]+i>mx)
        {
            mx = len[i]+i;
            po = i;
        }
        ans = max(ans,len[i]);
    }
    return ans  - 1;
}
int main()
{
    getline(cin,str);
    int l = init(str);
    cout<<Manacher(temp,l)<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Healer66/article/details/83115922