webVueBlog / LeetCode-HOT-100

力扣 (LeetCode) 🔥LeetCode HOT 100

Home Page:https://webvueblog.github.io/LeetCode-HOT-100/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

5. 最长回文子串

webVueBlog opened this issue · comments

5. 最长回文子串

Description

Difficulty: 中等

Related Topics: 字符串, 动态规划

给你一个字符串 s,找到 s 中最长的回文子串。

示例 1:

输入:s = "babad"
输出:"bab"
解释:"aba" 同样是符合题意的答案。

示例 2:

输入:s = "cbbd"
输出:"bb"

提示:

  • 1 <= s.length <= 1000
  • s 仅由数字和英文字母组成

Solution

Language: JavaScript

/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {
    let max = ''
    
    for (let i = 0; i < s.length; i++) {
        helper(i, i)
        helper(i, i+1)
    }

    function helper(l, r) {
        while(l >= 0 && r < s.length && s[l] === s[r]) {
            l--
            r++
        }
        const maxStr = s.slice(l + 1, r - 1 + 1)
        if (maxStr.length > max.length) max = maxStr
    }

    return max
}