Skip to content

Latest commit

 

History

History
44 lines (39 loc) · 1011 Bytes

5. 最长回文子串.md

File metadata and controls

44 lines (39 loc) · 1011 Bytes

给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。

示例 1:

输入: "babad"
输出: "bab"
注意: "aba" 也是一个有效答案。

示例 2:

输入: "cbbd"
输出: "bb"
/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {
    if (!s) return ''
    let start = 0, end = 0
    for (let i = 0; i < s.length; i++) {
        const len = expandAroundCenter(s, i, i)
        const len2 = expandAroundCenter(s, i, i+1)
        const maxLen = Math.max(len, len2)
        if ((end - start) < maxLen) {
            start = i - parseInt((maxLen - 1) / 2)
            end = i + parseInt(maxLen / 2)
        }
    }
    return s.substring(start, end + 1)
    function expandAroundCenter (s, left, right) {
        while(left >= 0 && right < s.length && s.charAt(left) === s.charAt(right)) {
            left--
            right++
        }
        return right - left - 1
    }
};