Manacher算法

Manacher算法

#include<bits/stdc++.h>
using namespace std;

const int N = 10000;
char s[N];	//字符串
int p[N];	//记录回文子串长度

//初始化
void Init(string str, char s[]) {
	s[0] = '$';		//避免边界判断
	int j = 1;
	s[j++] = '#';
	for (int i = 0; i < str.size(); i++) {
		s[j++] = str[i];
		s[j++] = '#';
	}
	s[j] = '\0';
}

//马拉车算法
int ManaCher(string str) {	
	int mx = 0;
	int id = 0;
	int max = -1;
	Init(str, s);				//初始化

	/*cout << s << endl;*/
	memset(p, 0, sizeof(p));
	for (int i = 1; s[i] != '\0'; i++) {
		//当已知最长回文字串的右界 mx > 当前坐标 i ,此时至少的回文长度为 p[2 * 已知回文字串的中心 - i](即为i与中心点id的对称点)
		//当已知回文长度p[2 * 已知回文字串的中心 - i] > mx - i (即超过已知最大回文的右界) 则 p[i] = mx - i(即它到右界的距离)
		p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1;	

		while (s[i + p[i]] == s[i - p[i]]) {
			p[i]++;
		}
		if (i + p[i] > mx) {
			mx = i + p[i];
			id = i;
		}
	}

	for (int i = 0; i < str.size() * 2 + 2; i++){
		/*cout << p[i] - 1;*/
		if (max < p[i] - 1) {
			max = p[i] - 1;
		}
	}

	/*cout << endl;*/
	
	return max;	//p【id】- 1 即为最长字串的长度
}
int main() {
	string str;
	cin >> str;
	cout << ManaCher(str) << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值