1089 The longest palindrome substring V2 (Manacher algorithm)

Base Time Limit: 1 second Space Limit: 131072 KB Score: 0  Difficulty: Basic
 collect
 focus on
Palindromic strings refer to left-right symmetrical strings such as aba, abba, cccbccc, and aaaa.
Input a string Str, output the length of the longest palindromic substring in Str.
Input
Enter Str (Length of Str <= 100000)
Output
Output the length L of the longest palindrome substring.
Input example
print
Output example
5

Idea: Manacher (horse carriage algorithm) https://blog.csdn.net/sunny_hun/article/details/79977680

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

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

intmain()
{
	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;//The rightmost position of the largest palindrome substring
    int id;//The center position of the largest palindrome substring
    int p[200200]; //The radius of the largest palindrome substring centered on i
    for(int i=1;i<n;i++)
    {
        if(i<mx)
            p[i]=min(p[2*id-i],mx-i); //The radius of i is left/right of 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) //The center of the largest palindrome substring becomes i
        {
            id=i;
            mx=i+p[i];
        }
        maxx=max(maxx,p[i]-1);
    }
    cout<<maxx<<endl;
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324530349&siteId=291194637