401 最长回文子串

// 401 最长回文子串.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
/*
http://oj.daimayuan.top/course/22/problem/933


给你一个字符串 s,字符串由小写字母组成,现在你需要求出 s中最长的回文子串的长度。

输入格式
一行一个字符串 s。

输出格式
输出一个整数表示答案。

样例输入
abbabbab
样例输出
7
数据规模
对于所有数据,保证 1≤|s|≤105,字符串均由小写字母构成。
*/

#include <iostream>
#include <cstring>

using namespace std;

//字符串哈希 和二分长度 然后顺序 逆序检测


int n, m, p[200002];
char s[100002], t[200003];

void manacher() {
	n = strlen(s + 1);
	m = 0;
	t[++m] = '#';
	for (int i = 1; i <= n; i++) {
		t[++m] = s[i]; t[++m] = '#';
	}
	int M = 0, R = 0;
	for (int i = 1; i <= m; i++) {
		if (i > R)
			p[i] = 1;
		else
			p[i] = min(p[2*M-i],R-i+1);
		while (i - p[i] > 0 && i + p[i] <= m && t[i - p[i]] == t[i + p[i]])
			++p[i];
		if (i + p[i] - 1 > R)
			M = i, R = i + p[i] - 1;
	}
	int ans = 0;
	for (int i = 1; i <= m; i++)
		ans = max(ans, p[i]);
	cout << ans - 1 << endl;
}


int main()
{
	cin >> s + 1;
	manacher();
	return 0;
}

posted on 2024-12-25 15:06  itdef  阅读(12)  评论(0)    收藏  举报

导航