1 class Solution { 2 public: 3 string longestPalindrome(string s) { 4 int maxLoc=0; 5 int maxNum=1; 6 const int stringSize=s.size(); 7 if(stringSize==1){ 8 return s; 9 } 10 11 for(int i=1; i!= 2*stringSize-1-1;++i){ 12 int a, b; 13 int num=1; 14 if(i%2==0){ //even 15 a=(int)(i-1)/2; 16 b=(int)(i+1)/2+1; 17 num=1; 18 } 19 else{ //old 20 a=(int)(i-1)/2; 21 b=(int)(i+1)/2; 22 num=0; 23 } 24 25 while(a>=0 && b<=stringSize){ 26 if(s[a] == s[b]){ 27 num=num+2; 28 a--; 29 b++; 30 } 31 else{ 32 break; 33 } 34 } 35 if(num>maxNum){ 36 maxNum=num; 37 maxLoc=i; 38 } 39 } 40 41 if(maxLoc%2==0){ 42 return s.substr(maxLoc/2-(maxNum-1)/2, maxNum); 43 } 44 else{ 45 return s.substr(maxLoc/2+1-maxNum/2, maxNum); 46 } 47 } 48 };
时间: 2024-10-27 05:43:40