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