【题目】: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.
【算法说明】:针对回文子串有一个很简单效果又很好的算法:manacher算法,大家可以亲切的称之为马拉车算法;
关于该算法的原理,可以参考博客:点击打开链接
【自己的代码】:
#include <iostream>
#include <string>
#include <queue>
#include <memory.h>
using namespace std;
class Solution {
public:
//add #
void preTreat(string &strIn, string &strOut)
{
int i = 0;
for (auto iter = strIn.begin(); iter != strIn.end(); ++iter)
{
strOut[i] = '#';
strOut[i + 1] = *iter;
i = i + 2;
}
strOut[i] = '#';
}
void manacher(string &strIn, string &strOut)
{
string strChanged;
strChanged.resize(strIn.size() * 2 + 1);
preTreat(strIn, strChanged);
cout << strChanged << endl;
int len = strChanged.size();
int *rad = (int *)malloc(sizeof(int)*len);
memset(rad, 0, sizeof(int)*len);
int maxIndex = 0;//记录目前为止,考察过的字符串中最大的索引值
int iOfMaxIndex = 0;//maxIndex 对应的i
int ans=0;//记录最长回文子串中心位置的索引编号
for (int i = 0; i < len; i++)
{
//这个if语句帮助减少了很大的计算量
if (maxIndex >= i)
{
rad[i] = min(rad[2 * iOfMaxIndex - i], maxIndex - i);
//cout << "after change,rad[i]: " << rad[i] << endl;
}
//以该点为中心,向两边扩展,考察最大的半径长度
while (((i - rad[i] - 1) >= 0) && ((i + rad[i] + 1) <= len) && (strChanged[i + rad[i] + 1] == strChanged[i - (rad[i] + 1)]))
{
rad[i]++;
}
//保存新的到最大索引的i
if (maxIndex < (i + rad[i]))
{
maxIndex = i + rad[i];
iOfMaxIndex = i;
}
if (rad[ans] < rad[i])
{
ans = i;
}
}
for (int i = (ans - rad[ans]); i <= ans + rad[ans]; ++i)
{
if (strChanged[i] != '#')
{
strOut.resize(strOut.size() + 1, strChanged[i]);
}
}
cout << strOut << endl;
delete rad;
}
string longestPalindrome(string s) {
string strAns;
manacher(s, strAns);
return strAns;
}
};
作者:香蕉麦乐迪--sloanqin--覃元元