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"
解法一:一般回文串分 奇数个数的回文串 偶数个数的回文串 比如
aba 属于奇数个数 abba 属于偶数个数。
思路是在区间[0…n]中 找出一个中心位置i,以该位置上的字符左(i-1 ) 右遍历(i+1),比较左右字符是否相等,更新最长回文串长度。
class Solution {
public:
string longestPalindrome(string s)
{
int i, j1, j2, left, right, length, count1, count2, max1,max2,id1,id2;
//left right 为以i为中心的左右隔壁字符位置 ,count1 count2 分别为奇偶回文串个数 id1,id2 分别记录奇偶回文串的 中心位置
string result; //存储最大回文串
count2 = max1=max2 = 0;
length = s.size();
for (i = 0; i < length; i++)
{
count1 = 1;
j1 = i;
left = j1 - 1;
right = j1 + 1;
while (left >= 0 && right <= length - 1 && s[left] == s[right]) //奇数回文串的情况
{
left--;
right++;
count1 += 2;
}
if (count1 > max1)
{
max1 = count1;
id1 = j1;
}
}
for (i = 0; i < length; i++) //偶数回文串的情况
{
count2 = 0;
j2 = i;
left = j2;
right = j2 + 1;
while (left >= 0 && right <= length - 1 && s[left] == s[right])
{
left--;
right++;
count2 += 2;
}
if (count2 > max2)
{
max2 = count2;
id2 = j2;
}
}
if (max1 > max2)
{
result = s.substr(id1 - (max1 / 2), max1);
}
else
{
result = s.substr(id2-(max2 / 2)+1, max2);
}
return result;
}
};
此算法复杂度 为O(n^2);
解法二 :通过在原有字符串基础上添加 n+1个‘#’使得字符串始终是奇数个,避免分类讨论。
class Solution {
public:
string longestPalindrome(string s) {
int max = 0;
int idx = 0;
string temp[2005];
//改造字符串
int j = 0;
for (int i = 0; i < s.length(); ++i)
{
temp[j++] = '#';
temp[j++] = s[i];
}
temp[j++] = '#';
temp[j] = '\0';
for (int i = 0; i <2 * s.length() + 1; ++i)
{
int j = i;
int z = i;
int count = 0;
//计算奇数最长回文字符串
while ((++z<(2 * s.length() + 1)) && (--j >= 0) && (temp[z] == temp[j]))
{
count++;
if (count > max)
{
max = count;
idx = i;
}
}
}
return s.substr((idx - max) / 2, max);
}
};