/*
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))
最新推荐文章于 2025-08-04 20:34:22 发布
本文介绍了一种用于查找字符串中最大回文子串的高效算法——Manacher算法,并提供了详细的实现步骤及C++代码示例。该算法通过对字符串进行特殊处理并利用已知回文信息减少不必要的比较,从而达到线性时间复杂度。
1070

被折叠的 条评论
为什么被折叠?



