Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
题意:找一个字符串的最大回文子字符串。
思路1:逆置字符串,然后用动态规划找出最长的相同的连续子串,时间复杂度为O(n^2), 提交后超时。
思路2:manacher算法。利用对称平衡信息,时间复杂度为O(n)。
class Solution {
public:
string longestPalindrome(string s) {
int size = s.size() * 2 + 1;
string str(size, '#');
for (int i = 0; i < s.size(); i++)
str[2 * i + 1] = s[i];
vector<int> p(size, 0);
int center = 0;
int right = 0;
for (int i = 1; i < size; i++){
if (i < right){//has reference
if (p[center * 2 - i] < right - i){
p[i] = p[center * 2 - i];
continue;
}
else{
p[i] = right - i;
}
}
int j = p[i]+1;
while (i - j >= 0 && i+j<size && str[i - j] == str[i + j]){
j++;
}
p[i] = j-1;
int tmp = i + p[i];
if (tmp > right){
center = i;
right = tmp;
}
}
vector<int>::iterator it = max_element(p.begin(), p.end());
int index = (it - p.begin()) / 2;
return s.substr(index - (*it) / 2, *it);
}
};