问题描述:
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"
解题思路:
从文中可以看出,题目让求得是最长回文字符串,那么,我们将利用从两边扩散的思想,最大值为2*i+1,遇奇数比较两边,遇偶数,比较前一个与自己。
class Solution {
public:
string longestPalindrome(string s) {
int Max=1,Maxf=0,Maxe=0;
for(int i=0;i<s.size();i++)
{
int end=findOdd(s,i);
if(Max<(end-i)*2+1){
Max=(end-i)*2+1;
Maxf=i+i-end;
Maxe=end;
}
end=findEven(s,i);
if(Max<(end-i)*2){
Max=(end-i)*2;
Maxf=i+i+1-end;
Maxe=end;
}
}
return s.substr(Maxf,Max);
}
int findOdd(string s,int center){
int i=center-1,j=center+1;
while(i>=0&&j<s.size()){
if(s[i]!=s[j]) return j-1;
i--;j++;
}
return j-1;
}
int findEven(string s,int center){
int i=center,j=center+1;
while(i>=0&&j<s.size()){
if(s[i]!=s[j])return j-1;
i--;j++;
}
return j-1;
}
};