class Solution {
public:
string longestPalindrome(string s) {
int bound = 0;
int id, max_pos = 0;
int new_len = 2*s.length() + 2;
vector<int> P(new_len, 1);
string new_str(new_len-1, '#');
//生成新串,用#填充
for(int i=0; i<s.length(); i++){
new_str[2*i+1] = s[i];
}
new_str = '$' + new_str + '\0'; //防止越界
//manacher算法
for(int i=1; i<new_len; i++)
{
if(i < bound)
{
P[i] = min(bound-i, P[2*id-i]);
}
while(new_str[i-P[i]] == new_str[i+P[i]])
{
P[i]++;
}
//更新id和bound
if(i+P[i] > bound)
{
bound = i+P[i];
id = i;
}
max_pos = P[i] > P[max_pos]?i:max_pos;
}
int len = P[max_pos]-1;
int start = (max_pos-P[max_pos])/2;
return s.substr(start,len);
}
};
bound:当前回文字符串右端最大值;
id:回文字符串右端最大值的中心点;
max_pos:当前最长回文字符串的中心位置;
P[i]:即计算以i位置为中心的最长回文字符串右端到i的距离。