class Solution {
public:
string longestPalindrome(string s) {
string t = "$#";
for (int i = 0; i < s.size(); ++i) {
t += s[i];
t += '#';
} //利用了 Manacher's Algorithm 马拉车算法
int nl = t.size();
int p[nl] = { 0 }, id = 0, mx = 0, resId = 0, resMx = 0;
for (int i = 1; i < t.size(); ++i) {
p[i] = mx > i ? min(p[2 * id - i], mx - i) : 1;
while (t[i + p[i]] == t[i - p[i]]) ++p[i];
if (mx < i + p[i]) {
mx = i + p[i];
id = i;
}
if (resMx < p[i]) {
resMx = p[i]; //用resMx记录最大的半径,用resId记录原点!
resId = i;
}
}
return s.substr((resId - resMx) / 2, resMx - 1); //注意此时输出的是原来数组,不是后来新建的数组,所以控制好输出的起始位置和长度!
}
};
参考博客:
https://www.cnblogs.com/grandyang/p/4464476.html
Manacher算法:
https://subetter.com/algorithm/manacher-algorithm.html
刷题总结:
求回文数可利用Manacher算法,大大降低时间复杂度和空间复杂度!