一、题目
二、思路
1、最长回文子串,不是最长回文子序列;
最长回文子串是要连续的
最长回文子序列可以不连续
2、采用补充“#”的方法,使整个字符串都是奇数个
3、for循环遍历,每一个都往左右两边扩散,找到相等的,并且不为“#”的就加进去
如果不相等就进行下一个判断
三、代码
class Solution
{
public:
int getLongestPalindrome(string A, int n)
{
if (n == 0 || n == 1)
{
return n;
}
//添加'#''
string B = "";
for (int i = 0; i < n; ++i)
{
B = B + A[i] + '#';
}
B = B.substr(0, B.length() - 1);
int len = B.length();
int Count = 0;
//每一个都往左右两边扩散
for (int i = 0; i < len; ++i)
{
int temp = 0;
if (B[i] != '#')
{
temp = 1;
}
int left = i - 1;
int right = i + 1;
while (left >= 0 && right < len)
{
if (B[left] == B[right])
{
if (B[right] != '#')
{
temp += 2;
Count = Count > temp ? Count : temp;
}
left--;
right++;
}
else
{
break;
}
}
}
return Count;
}
};