#include<bits/stdc++.h>
#define REP(i, a, b) for(int i = (a); i < (b); ++i)
#define DREP(i, a, b) for(int i = (a); i >= (b); --i)
#define debug(...) fprintf(stderr, __VA_ARGS__)
using namespace std;
const int maxn = 100000 + 10;
int len[maxn << 1];
char str[maxn], tran[maxn << 1];
int init(char *s) {
int l = strlen(s);
tran[0] = '@';
for(int i=1; i<=2*l; i+=2) {
tran[i] = '#';
tran[i+1] = s[i/2];
}
tran[l*2 + 1] = '#';
tran[l*2 + 2] = '$';
tran[l*2 + 3] = '\0';
return l*2 + 1;
}
int manacher(char *st) {
int p = 0, p0 = 0, ans = 0;
int l = strlen(st);
for(int i=1; i<=l; i++) {
if(p > i)
len[i] = min(p-i, len[2*p0 - i]);
else
len[i] = 1;
while(st[i - len[i]] == st[i + len[i]]) len[i]++;
if(i + len[i] > p) {
p = len[i] + i;
p0 = i;
}
ans = max(ans, len[i]);
}
return ans - 1;
}
int main() {
#ifndef ONLINE_JUDGE
freopen("data.txt", "r", stdin);
freopen("ans.txt", "w", stdout);
#endif
while(scanf("%s", str) == 1) {
init(str);
cout << manacher(tran) << endl;
}
return 0;
}
Manacher算法求最长回文串
最新推荐文章于 2024-04-07 11:28:48 发布