1089 最长回文子串 V2(Manacher算法)

基准时间限制:1 秒 空间限制:131072 KB 分值: 0  难度:基础题
 收藏
 关注
回文串是指aba、abba、cccbccc、aaaa这种左右对称的字符串。
输入一个字符串Str,输出Str里最长回文子串的长度。
Input
输入Str(Str的长度 <= 100000)
Output
输出最长回文子串的长度L。
Input示例
daabaac
Output示例
5

思路:Manacher(马拉车算法)https://blog.csdn.net/sunny_hun/article/details/79977680

#include<iostream>
#include<cstring>
using namespace std;

char str[100100];
char s[200200];

int main()
{
	cin>>str;
    int i,j,maxx=1;
    int n=strlen(str);
    for(i=n;i>=1;i--)
    {
        s[i*2+1]='#';
        s[i*2]=str[i-1];
    }
    s[0]='$';
    s[1]='#';
    n=strlen(s);
    s[n]='\0';
    int mx;//最大回文子串的最右边位置
    int id;//最大回文子串的中心位置
    int p[200200];  //以i为中心的最大回文子串半径
    for(int i=1;i<n;i++)
    {
        if(i<mx)
            p[i]=min(p[2*id-i],mx-i);  //i的半径在mx左/右,p[j],mx-i
        else
            p[i]=1;
        while(s[i-p[i]]==s[i+p[i]])
            p[i]++;
        if(i+p[i]>mx)  //最大回文子串中心变成i
        {
            id=i;
            mx=i+p[i];
        }
        maxx=max(maxx,p[i]-1);
    }
    cout<<maxx<<endl;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/sunny_hun/article/details/79977956
今日推荐