Given a string S, find the longest palindromic substring in S. You may assume that the maximum length of S is 1000, and there exists one unique longest palindromic substring.
两边扩展法:
bool isPalindrome(string &s, int start, int end){
while(start < end){
if(s[start] != s[end])
return false;
start ++;
end --;
}
return true;
}
string longestPalindrome(string s) {
int longest = 0;
int start = 0;
int end = 0;
for(int i = 0; i < s.size(); i ++){
//find s[i] from end of S
for(int j = s.size() - 1; j >= i; j --){
if(j - i + 1 <= longest)
break;
if(isPalindrome(s, i, j)){
if(j - i + 1 > longest){
longest = j - i + 1;
start = i;
end = j;
}
break;
}
}
}
return s.substr(start, longest);
}