马拉车算法是寻找最长回文子串的高效算法,时间复杂度为O(n)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string longestPalindrome(string s) {
// 步骤1: 预处理,在字符间插入特殊字符'#'
string t = "#";
for (char c : s) {
t += c;
t += "#";
}
// 步骤2: 初始化变量
int n = t.length();
vector<int> P(n, 0); // P[i]存储以i为中心的回文半径
int C = 0; // 当前回文串的中心
int R = 0; // 当前回文串的右边界
int maxLen = 0; // 最长回文子串的长度
int centerIndex = 0; // 最长回文子串的中心位置
// 步骤3: 主循环,计算每个位置的回文半径
for (int i = 0; i < n; i++) {
// 确定初始回文半径
if (i < R) {
int mirror = 2 * C - i; // i关于C的对称点
P[i] = min(R - i, P[mirror]); // 利用对称性
}
// 尝试扩展回文
int a = i + (1 + P[i]);
int b = i - (1 + P[i]);
while (a < n && b >= 0 && t[a] == t[b]) {
P[i]++;
a++;
b--;
}
// 更新C和R
if (i + P[i] > R) {
C = i;
R = i + P[i];
}
// 更新最长回文子串信息
if (P[i] > maxLen) {
maxLen