Description:
Given a string S, find the longest palindromic substring in S.
You may assume that the maximum length of S is 1000, and there exist
one unique longest palindromic substring.
分析见:
https://segmentfault.com/a/1190000003914228
#include <iostream>
#include <string>
using namespace std;
int manacher(string str) //manacher算法 求最长回文字符串
{
//插入没有在数组中出现的符号,这里用"#", abba->#a#b#b#a#
string NewStr;
NewStr += "#";
for (int i=0; i < str.size(); i++)
{
NewStr += str[i];
NewStr += "#";
}
int RL[NewStr.size()]; //回文半径数组
int MaxRight = 0, pos = 0, Maxlen = 0;
for(int i = 0; i < NewStr.size(); i++){
if ( i < MaxRight)
RL[i] = min(RL[2*pos-i],MaxRight-i);
else
RL[i] = 1;
//扩展,注意边界
while ((i-RL[i] >= 0) && (i+RL[i] < NewStr.size()) && (NewStr[i-RL[i]] == NewStr[i+RL[i]])) {
RL[i] += 1;
}
//更新MaxRight,pos
if ((i+RL[i]-1) > MaxRight)
{
MaxRight = i+RL[i]-1;
pos = i;
}
//更新最长回文串的长度
Maxlen = max(Maxlen,RL[i]);
}
return Maxlen-1;
}
int main(int argc, char const *argv[]) {
string str = "abba";
string str2 = "123454321";
string str3 = "acdeg";
std::cout <<manacher(str)<< std::endl;
std::cout <<manacher(str2)<< std::endl;
std::cout <<manacher(str3)<< std::endl;
return 0;
}
测试: