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.
从每个位置,向两边开始扫描。
</pre><pre name="code" class="cpp">class Solution {
public:
string find_longest(string s,int c1,int c2){
int left=c1;
int right=c2;
while(s[left]==s[right]&&left>=0&&right<(int)s.size()){
left--;
right++;
}
return s.substr(left+1,right-left-1);
}
string longestPalindrome(string s) {
string longest=s.substr(0,1);
int len=s.size();
for(int i=0;i<len-1;i++){
string sub1=find_longest(s,i,i);
if(sub1.size()>longest.size())
longest=sub1;
string sub2=find_longest(s,i,i+1);
if(sub2.size()>longest.size())
longest=sub2;
}
return longest;
}
};