Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: “babad” Output: “bab” Note: “aba” is also a valid answer.
Example 2:Input: “cbbd” Output: “bb”
求一个字符串的最长回文子串~
中心枚举法,从一个字符出发,如果它的左边字符等于右边字符,那么继续向两边扩展。需要注意的是,回文子串的长度可能是奇数也可能是偶数的情况。时间复杂度是O(n^2),空间复杂度O(1).
string longestPalindrome(string s) {
int len = s.size();
if(len <= 1)
return s;
int maxsize = 0;
string maxstr;
for(int i = 1;i<len;i++)
{
int left = i - 1;
int right = i; //right = i 判断回文子串是偶数的情况
while(left >= 0 && right < len && s.at(left) == s.at(right) )
{
left--;
right++;
}
int size = (right-1) - (left+1) + 1;
if(size > maxsize)
{
maxsize = size;
maxstr = s.substr(left+1,size);
}
left = i - 1;
right = i+1; //right = i + 1 判断回文子串是偶数的情况
while(left >= 0 && right < len && s.at(left) == s.at(right) )
{
left--;
right++;
}
size = (right-1) - (left+1) + 1;
if(size > maxsize)
{
maxsize = size;
maxstr = s.substr(left+1,size);
}
}
return maxstr;
}