题目分析
1. 这题是要求找最长回文子序列,比较普通的做法是直接枚举中点,然后向两侧扩展,这样是O(N^2)的算法。
2. 不过可以用 Manacher 算法在O(N)以内找出来,参考了这篇博客文章的题目,感觉讲得很详细了, 还有配图, 就不额外进行分析了。https://segmentfault.com/a/1190000003914228
class Solution {
public:
string longestPalindrome(string s) {
int len = s.length();
string str;
str.push_back('#');
for (int i = 0; i < len; i++) {
str.push_back(s[i]);
str.push_back('#');
}
len = str.length();
vector<int> p(len, 0);
int maxRight = 0;
int center = 0;
int i = 0, j = 0;
int max = -1, maxindex = 0;
for (int i = 0; i < len; i++) {
if (i < maxRight) {
p[i] = (i + p[center - (i - center)] <= maxRight) ? p[center - (i - center)] : maxRight - i;
j = i + p[i];
}
else j = i;
while (i - (j - i) - 1 >= 0 && j + 1 < len && str[j + 1] == str[i - (j - i) - 1])
j++;
p[i] = j - i;
if (j > maxRight) {
maxRight = j;
center = i;
}
if (p[i] > max) {
max = p[i];
maxindex = i;
}
}
string result = "";
for (int k = maxindex - max; k <= maxindex + max; k++) {
if (str[k] != '#') result.push_back(str[k]);
}
return result;
}
};