HDU3068 Manacher求最长回文

manacher算法:可以在O(n)的时间内求出一个字符串的最长回文的大小。

算法的思想是利用前边已求出的回文子串,对于以当前位置为中心求回文串不必从1开始向两边遍历。

具体算法可以参考这篇文章:http://blog.csdn.net/dyx404514/article/details/42061017

————————————————————————————————————————————————————————————————

题目:HDU3068

一道裸的求最大回文模板的题。

代码:

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
const int N = 110005;
char str1[N], str2[N<<1];
int Len[N<<1];
int l;
void init(){
	l = strlen(str1);
	str2[0] = '@';
	for(int i = 1; i <= l*2; i+=2){
		str2[i] = '#';
		str2[i+1] = str1[i/2];
	}
	str2[l*2+1] = '#';
	str2[l*2+2] = 0;
}
int manacher(){
	int len = l * 2 + 1;
	int mx = 0, pos = 0, ans = 0;
	for(int i = 1; i <= len; i++){
		if(mx <= i)
			Len[i] = 1;
		else
			Len[i] = min(mx-i, Len[2*pos - i]);
		while(str2[i+Len[i]] == str2[i-Len[i]])
			Len[i] ++;
		if(Len[i] + i > mx){
			pos = i;
			mx = Len[i] + i;
		}
		ans = max(ans, Len[i]);
	}
	return ans - 1;
}
int main(){
	while(~scanf("%s", str1)){
		init();
		int ans = manacher();
		printf("%d\n", ans);
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值