码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode : 5. Longest Palindromic Substring

时间:2016-04-28 11:58:25      阅读:225      评论:0      收藏:0      [点我收藏+]

标签:

技术分享

 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 };

 

LeetCode : 5. Longest Palindromic Substring

标签:

原文地址:http://www.cnblogs.com/sthv/p/5441824.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!