LeetCode : 5. Longest Palindromic Substring

 1 class Solution {
 2 public:
 3     string longestPalindrome(string s) {
 4         string result="";
 5         int length=s.length();
 6         int counter_Max=0;
 7         int pos_Start=0,pos_End=0;
 8         
 9         if(length<=2){
10             if(s[0]==s[1]) return s;
11             else{
12                 result+=s[0];
13                 return result;
14             }
15         }
16          
17         //  XXX...A...XXX style
18         for(int i=0;i<length;i++){
19             //search 
20             int counter_Thisloop=1;
21             int j=i-1;
22             for(;(j>=0)&&((2*i-j)<length)&&(s[j]==s[2*i-j]);j--){
23                 counter_Thisloop=counter_Thisloop+2;
24             }
25             if(counter_Thisloop>counter_Max){
26                 counter_Max = counter_Thisloop;
27                 pos_Start=j+1;
28                 pos_End=2*i-j-1;
29             }
30         }
31         //  XXX...AA...XXX style
32         for(int i=0;i<length;i++){
33             //search 
34             int counter_Thisloop=0;
35             int j=i-1;
36             for(;(j>=0)&&((2*i-j-1)<length)&&(s[j]==s[2*i-j-1]);j--){
37                 counter_Thisloop=counter_Thisloop+2;
38             }
39             if(counter_Thisloop>counter_Max){
40                 counter_Max = counter_Thisloop;
41                 pos_Start=j+1;
42                 pos_End=2*i-j-2;
43             }
44         }
45         
46         for(int k=pos_Start;k<=pos_End;k++){
47             result+=s[k];
48         }
49         return result;
50         
51     }
52 };

 

posted @ 2016-04-28 11:00  盛小胖  阅读(104)  评论(0编辑  收藏  举报