hdu 3068 最长回文 (Manacher O(n) ) (扩展KMP和后缀数组也都可以做 O(nlogn))

/*
    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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值