https://www.felix021.com/blog/read.php?2040
这个网址上写的很详细,很容易看懂
#include<bits/stdc++.h>
using namespace std;
int p[1005];
string change(string s, int l)//改变字符串,变成奇数长度的串
{
string cs = "";
for (int i = 0; i<l; i++)
{
cs = cs+'#';
cs = cs + s[i];
}
cs = '@' + cs + '#';
return cs;
}
void manacher(string s, int l)
{
int mr = 0, mm = 0;
for (int i = 1; i<l; i++)
{
p[i] = mr>i ? min(p[2 * mm - i], mr - i) : 1;//如果maxright>i那么以i为中心的回文串包括在maxmid里面,并且2*mm-i这个点,是i关于maxmid对称的点,p[i]=p[2*mm-1];
while (s[i - p[i]] == s[i + p[i]])
p[i]++;
if (i + p[i]>mr)//更新maxright
{
mr = i + p[i];
mm = i;
}
}
}
int main()
{
string s, cs;
int l;
cin >> cs;
l = cs.size();
s = change(cs, l);
l = s.size();
manacher(s, l);
int ans = 0;
for (int i = 1; i<l; i++)
{
ans = max(ans, p[i]-1);
}
cout << ans << endl;
return 0;
}