Manacher算法解释:http://tarokuriyama.com/projects/palindrome2.php
class Solution {
public:
string longestPalindrome(string s) {
//O(N^2)超时
if(s.empty())
{
return "";
}
int start=0,end=-1;
char *table = new char[s.size()*s.size()];
memset(table,-1,s.size()*s.size()*sizeof(char));
for(int i=0;i<s.size();i++)
{
for(int j=i;j<s.size();j++)
{
if(isPalin(s,i,j,table) && (j-i+1)>(end-start+1))
{
start=i;
end=j;
}
}
}
return s.substr(start,end-start+1);
}
char isPalin(const string &s,int i,int j,char *table)
{
if(table[i*s.size()+j]!=-1)
{
return table[i*s.size()+j];
}
if(i>j){
table[i*s.size()+j]=0;
}
else if(i==j){
table[i*s.size()+j]=1;
}else if(i+1==j){
table[i*s.size()+j]=(s[i]==s[j]?1:0);
}else{
table[i*s.size()+j]=isPalin(s,i+1,j-1,table) && (s[i]==s[j]);
}
return table[i*s.size()+j];
}
};
class Solution {
//从网上找的一份Manacher算法的实现,稍微修改了一下
public:
// Transform S into T.
// For example, S = "abba", T = "^#a#b#b#a#$".
// ^ and $ signs are sentinels appended to each end to avoid bounds checking
string preProcess(string s) {
int n = s.length();
if (n == 0) return "^$";
string ret = "^";
for (int i = 0; i < n; i++) ret += "#" + s.substr(i, 1);
ret += "#$";
return ret;
}
string longestPalindrome(string s) {
string T = preProcess(s);
const int n = T.length();
// 以 T[i] 为中心,向左/右扩张的长度,不包含 T[i] 自己,
// 因此 P[i] 是源字符串中回文串的长度
int P[n];
int max_len = 0;
int center_index = 0;
int C = 0, R = 0;
for (int i = 1; i < n - 1; i++) {
int i_mirror = 2 * C - i; // (i_mirror+i)/2==c
P[i] = (R > i) ? min(R - i, P[i_mirror]) : 0;
// Attempt to expand palindrome centered at i
while (T[i + 1 + P[i]] == T[i - 1 - P[i]])
P[i]++;
// If palindrome centered at i expand past R,
// adjust center based on expanded palindrome.
if (i + P[i] > R) {
C = i;
R = i + P[i];
}
//find the max
if (P[i] > max_len) {
max_len = P[i];
center_index = i;
}
}
return s.substr((center_index - 1 - max_len) / 2, max_len);
}
};