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

5. Longest Palindromic Substring

时间:2017-10-07 18:37:52      阅读:127      评论:0      收藏:0      [点我收藏+]

标签:start   func   return   amp   bst   param   mic   not   ++   

5. Longest Palindromic Substring

 

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 /**
 2  * @param {string} s
 3  * @return {string}
 4  */
 5 var longestPalindrome = function(s) {
 6     var start = 0;
 7     var max_len = 0;
 8     var len = s.length;
 9     if(len < 2){
10         return s;
11     }
12     
13   
14 
15     for(var i =0;i< len - 1;i++){
16         
17           check(i,i);
18           check(i,i+1);
19     }
20     
21     return s.substring(start,start+max_len);
22     
23     function check(left,right){
24         
25        while(left>=0 && right < len && s.charAt(left) == s.charAt(right)){
26             left--;
27             right++;
28         }
29         
30         if(right-left-1 > max_len){
31             
32             max_len = right-left-1;
33             start = left+1;
34            
35         }
36         
37     }
38     
39 };

 

5. Longest Palindromic Substring

标签:start   func   return   amp   bst   param   mic   not   ++   

原文地址:http://www.cnblogs.com/huenchao/p/7635227.html

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