HDU 3068【manacher算法】

本文详细介绍Manacher算法原理及其实现过程,用于求解给定字符串中的最长回文子串长度。通过具体实例和代码解析,帮助读者理解并掌握这一高效算法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接 :http://acm.hdu.edu.cn/showproblem.php?pid=3068

Problem Description

给出一个只由小写英文字符a,b,c...y,z组成的字符串S,求S中最长回文串的长度.
回文就是正反读都是一样的字符串,如aba, abba等

Input

输入有多组case,不超过120组,每组输入为一行小写英文字符a,b,c...y,z组成的字符串S
两组case之间由空行隔开(该空行不用处理)
字符串长度len <= 110000

Output

每一行一个整数x,对应一组case,表示该组case的字符串中所包含的最长回文长度.

Sample Input

aaaa

abab

Sample Output

4

3

manacher算法https://blog.youkuaiyun.com/dyx404514/article/details/42061017

代码:

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <queue>
#include <stack>
#include <set>
#include <map>
#define INF 0x3f3f3f3f
#define LL long long
using namespace std;
const int maxn=1000005;
int k,m;
char str[maxn];
char tmp[maxn<<1];
int Len[maxn];
int init(char *st){
	int i,len=strlen(st);
	tmp[0]='@';//字符串开头加一个字符,防止越界 
	for(int i=1;i<=2*len;i+=2){
		tmp[i]='#';
		tmp[i+1]=st[i/2];
	}
	tmp[2*len+1]='#';
	tmp[2*len+2]='$';//字符串结尾加一个字符,防止越界 
	tmp[2*len+3]=0;
	return 2*len+1;
}
int manacher(char *st,int len){
	int mx=0,ans=0,po=0;//mx为之前计算回文子串的右端点的最大值,po为取得这个最大值的位置 
	for(int i=1;i<=len;i++){
		if(mx>i)
			Len[i]=min(mx-i,Len[2*po-i]);//在len[j]和mx-i中取最小 
		else Len[i]=1;//如果i>=mx,要从头开始匹配 
		while(st[i-Len[i]]==st[i+Len[i]])
			Len[i]++;
		if(Len[i]+i>mx){//若新计算的回文串右端点位置大于mx,要更新po和mx的值 
			mx=Len[i]+i;
			po=i;
		}
		ans=max(ans,Len[i]);
	}
	return ans-1;//返回len[i]中的最大值-1即为原串中的最长回文子串的长度 
}
int main(){
	while(~scanf("%s",str)){
		int len=init(str);
		int ans=manacher(tmp,len);
		printf("%d\n",ans);
	}
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值