题目链接:点击打开链接
Manacher算法的模板题, Manacher算法用于求最长回文串的长度及其他拓展, 套板子即可, 最长为p[i] - 1.
AC代码:
#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 110000 + 10;
char s[MAXN * 2];
int p[MAXN * 2];
int main(int argc, char const *argv[])
{
while(scanf("%s", s) != EOF) {
int len = strlen(s), ans = 0, id = 0;
for(int i = len; i >= 0; --i) {
s[i * 2 + 2] = s[i];
s[i * 2 + 1] = '#';
}
s[0] = '$';
for(int i = 2; i < 2 * len + 1; ++i) {
if(p[id] + id > i) p[i] = min(p[id * 2 - i], p[id] + id - i);
else p[i] = 1;
while(s[i - p[i]] == s[i + p[i]]) ++p[i];
if(id + p[id] < i + p[i]) id = i;
ans = max(ans, p[i]);
}
printf("%d\n", ans - 1);
}
return 0;
}