Manacher算法是一个用来查找一个字符串中的最长回文子串(不是最长回文序列)的线性算法。它的优点就是把时间复杂度为O(n^2)的暴力算法优化到了O(n)

本质是对中心扩展算法的优化!

alt text

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public:
string longestPalindrome(string s) {
string str = "";
str += '$';
for (auto ch : s) {
str += '#';
str += ch;
}
str += '#';

int n = str.size();
vector<int> d(n + 1, 1);
int l = 1, r = 1;
int mx = 0;
int p = 0;
for (int i = 2; i < str.size(); i++) {
if (i <= r) {
d[i] = min(d[l + r - i], r - i + 1);
}
while (str[i + d[i]] == str[i - d[i]]) {
d[i]++;
}
if (d[i] > mx) {
mx = d[i];
p = i;
}
if (i + d[i] - 1 > r) {
r = i + d[i] - 1;
l = i - d[i] + 1;
}
}
string ans = "";
// #a#b#b#a#
for (int i = p - mx + 1; mx - 1 >= 1; i++) {
if (str[i] != '#') {
mx--;
ans += str[i];
}
}
return ans;
}
};