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"
1 class Solution { 2 public: 3 string longestPalindrome(string s){ 4 int len=s.size(); 5 string s1(1,s[0]); 6 int maxlen=1; 7 if(len<2) 8 return s; 9 10 for(int i=0;i<len-1;i++) 11 { 12 string p1=helper(s,i,i); 13 if (p1.size()>maxlen) 14 { 15 s1=p1;//奇数回文数 16 maxlen=p1.size(); 17 } 18 19 string p2=helper(s,i,i+1); 20 if (p2.size()>maxlen) 21 { 22 s1=p2;//偶数回文数 23 maxlen=p2.size(); 24 } 25 } 26 return s1; 27 } 28 string helper(string s,int c1,int c2)//中心扩展法,定义中心位置c1、c2 29 { 30 int i=c1,j=c2; 31 while(i>=0&&j<s.size()&&s[i]==s[j]) 32 { 33 i--; 34 j++; 35 } 36 return s.substr(i+1,j-i-1);//(j-1)-(i+1)+1 37 38 } 39 40 };