问题描述:
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example:
Input: “babad”
Output: “bab”
Note: “aba” is also a valid answer.
Example:
Input: “cbbd”
Output: “bb”
解决方案:
求最大回文子串,我之前正好看过Manacher算法解决最大回文子串的问题,算法的时间复杂度仅为O(n),这个算法可以将长度为奇数和偶数的回文子串统一处理,具体算法的描述请看我的文章http://blog.youkuaiyun.com/u013362955/article/details/71516107
代码
string longestPalindrome(string str) {
string str0;
str0 += "$#";
for(int i = 0; i < str.size(); i++)
{
str0 += str[i];
str0 += "#";
}
string s = findBMstr(str0);
return s;
}
string findBMstr(string& str)
{
int *p = new int[str.size() + 1];
memset(p, 0, sizeof(p));
int mx = 0, id = 0; //mx记录最大边界,id记录回文中心点
for(int i = 1; i <= str.size(); i++)
{
if(mx > i)
{
p[i] = (p[2*id - i] < (mx - i) ? p[2*id - i] : (mx - i));
}
else
{
p[i] = 1;
}
while(str[i - p[i]] == str[i + p[i]])
p[i]++;
if(i + p[i] > mx)
{
mx = i + p[i];
id = i;
}
}
int max = 0, ii;
for(int i = 1; i < str.size(); i++)
{
if(p[i] > max)
{
ii = i;
max = p[i];
}
}
max--;
string s;
int start = ii - max ;
int end = ii + max;
for(int i = start; i <= end; i++)
{
if(str[i] != '#')
{
s += str[i];
}
}
// cout << endl;
delete p;
return s;
}