/*
Subject: Manacher Algorithm
Author : a_clay
Created Date : 2011-12-26
Sample : hdu 3068
*/
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
#include <algorithm>
#define Bug cout << "here\n";
using namespace std;
const int N = 110005;
char str1[N];
char str[2*N]; //start from index 1
int rad[2*N], nn, n;
void Manacher(int *rad, char *str, int n) { /* str 是这样一个字符串(下标从1开始):
举例:若原字符串为"abcd",则str为"$#a#b#c#d#",最后还有一个终止符。
n为str的长度,若原字符串长度为nn,则n=2*nn+2。
rad[i]表示回文的半径,即最大的j满足str[i-j+1...i] = str[i+1...i+j],
而rad[i]-1即为以str[i]为中心的回文子串在原串中的长度*/
int i, id = 0, mx = 0;
for(i = 1; i < n; i++) {
if(mx > i) {
rad[i] = min(rad[2*id - i], mx - i);
}
else rad[i] = 1;
while(str[i+rad[i]] == str[i-rad[i]]) rad[i]++;
if(rad[i] + i > mx) {
mx = i + rad[i];
id = i;
}
}
}
int main() {
int i, ans;
while(cin >> str1) {
nn = strlen(str1);
n = 2*nn + 2;
str[0] = '$';
str[n] = '\0';
for(i = 0; i <= nn; i++) {
str[2*i + 1] = '#';
if(i != nn) str[2*i + 2] = str1[i];
}
memset(rad, 0, sizeof(rad));
Manacher(rad, str, n);
ans = 1;
for(i = 0; i < n; i++) {
ans = max(rad[i], ans);
}
cout << ans - 1 << endl;
}
return 0;
}
hdu 3068 最长回文 (Manacher O(n) ) (扩展KMP和后缀数组也都可以做 O(nlogn))
最新推荐文章于 2021-11-23 17:45:36 发布