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"
代码:
class Solution {
public:
string longestPalindrome(string s) {
int len=s.length();
int i,j;
int mlen=0;
string ms="";
for(i=0;i<len;i++){
for(j=1;;j++){
if(s[i]!=s[i+j])
break;
}
j--;
int k=1;
while(i-k>=0 && i+j+k<len){
if(s[i-k]==s[i+j+k])
k++;
else
break;
}
k--;
if(j+2*k+1>mlen){
mlen=j+2*k+1;
ms=s.substr(i-k,j+2*k+1);
}
}
return ms;
}
};
时间复杂度O(n^2)过了。代码的思路是对回文串不断两边扩展(先单边扩展相同字符,然后两边扩展对称字符)。