您的位置:首页 > 其它

Leetcode 5. 最长回文子串

2018-03-02 12:14 513 查看
Manacher算法

#define L(x) (x-P[x])
#define R(x) (x+P[x])
#define LS(x,y) (2*x-y)
class Solution {
public:
string longestPalindrome(string s) {
int P[2010], Po, mx_Po;
string str = "@", ans;
char tmp[3] = "##";
for (auto x : s)
tmp[1] = x, str.append(tmp);
str.append("#!");
Po = mx_Po = 0;
for (int i = 1; i < str.size() - 1; ++i) {
if (R(Po) > i) P[i] = min(R(Po) - i, P[LS(Po, i)]);
else P[i] = 0;
while (str[L(i) - 1] == str[R(i) + 1]) ++P[i];
if (R(i) > R(Po)) Po = i;
if (P[i] > P[mx_Po]) mx_Po = i;
}
s = string(str, L(mx_Po), 2 * P[mx_Po] + 1);
for (auto x : s)
if (x != '#') ans += x;
return ans;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: