AcWing 139. 回文子串的最大长度——贴个manacher算法的题解
原题链接
中等
作者:
虹之间
,
2020-01-29 20:06:02
,
所有人可见
,
阅读 1011
#include <iostream>
#include <cstdio>
using namespace std;
struct P{
int l, r, len; // 起点,终点,实际长度
};
int manacher(string &s) {
if(s.length() < 2) return s.length();
string t;
for(auto c: s) t += c, t += '#';
int n = t.length() - 1;
int d[n] = {0};
int res = 0;
for(int i = 0, l = 0, r = -1; i < n; i++)
{
int k = (i > r) ? 1 : min(d[l + r - i], r - i);
while(0 <= i - k && i + k < n && t[i - k] == t[i + k]) k++;
d[i] = k--;
int start = i - d[i] + 1;
int len = t[start] == '#' ? (d[i] * 2 - 2) / 2 : (d[i] * 2) / 2;
if(len > res) res = len;
if(i + k > r) l = i - k, r = i + k;
}
return res;
}
int main()
{
string s;
int tot = 0;
while(cin >> s && s[0] != 'E')
{
printf("Case %d: %d\n", ++tot, manacher(s));
}
return 0;
}