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 1:

Input: "babad"

Output: "bab"

Note: "aba" is also a valid answer.

Example 2:

Input: "cbbd"

Output: "bb"

遇到类似的对称问题,首先考虑找对称轴。

 

/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {
    var len = s.length;
    var size = 0;
    var str = "";
    for(var i = 0; i < len; i++) {
        for(var j = 0; j < 2; j++) {
            var left = i, right = i+j;
            while(s[left] && s[left] == s[right]) {
                left--;
                right++;
            }
            if(right-left-1 >= size) {
                str = s.slice(left+1, right);
                size = right-left-1;
            }
        }
    }
    return str;
};

 

  

 

上一篇:[LeetCode] 594. Longest Harmonious Subsequence


下一篇:LeetCode算法题-Longest Univalue Path(Java实现)