Longest Palindromic Substring
Description
Given a string s, find the longest palindromic substring in s. You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad" Output: "bab" Note: "aba" is also a valid answer.
Example 2:
Input: "cbbd" Output: "bb"
Solution(javascript)
/**
* @param {string} s
* @return {string}
*/
var longestPalindrome = function(s) {
var len = s.length;
var pal = "";
var offset = 1;
for(var i = 0; i < len; i++){
if(i < len - 1 && s.charAt(i) == s.charAt(i+1)){
while(i-offset >= 0 && i+1+offset < len
&& s.charAt(i-offset) == s.charAt(i+1+offset)){
offset ++;
}
var palEven = s.substring(i+1-offset, i+1+offset);
pal = pal.length >= palEven.length ? pal : palEven;
offset = 1;
}
while(i-offset >= 0 && i+offset < len
&& s.charAt(i-offset) == s.charAt(i+offset)){
offset ++;
}
var palOdd = s.substring(i+1-offset, i+offset);
pal = pal.length >= palOdd.length ? pal : palOdd;
offset = 1;
}
return pal;
};