马拉车算法(回文子串长度)

夜深人静想算法 / 2024-12-29 / 原文

#include<bits/stdc++.h>

using namespace std;

#define int long long

const int Max=100000;

char s[Max*2+5];

char str[Max*2+5];

int dp[Max*2+5];

void mc()

{

int n=strlen(s+1);

str[0]='s';

int j=1;

for(int i=1;i<=n;i++)

{

str[j++]='#';

str[j++]=s[i];

}

str[j++]='#';

str[j++]='@';

int pos=0,right=0;

for(int i=0;i<j;i++)

{

if(i<right)

{

dp[i]=min(dp[2*pos-i],right-i);

}

else

{

dp[i]=1;

}

while(str[i+dp[i]]==str[i-dp[i]])dp[i]++;

if(dp[i]+i>right)

{

right=dp[i]+i;

pos=i;

}

}

int mx=0;

for(int i=0;i<j;i++)

{

mx=max(dp[i]-1,mx);

}

cout<<mx<<endl;

}

signed main()

{

scanf("%s",s+1);

mc();

return 0;

}