1684838553 / arithmeticQuestions

程序员的算法趣题
2 stars 0 forks source link

最长回文字符串 #5

Open 1684838553 opened 2 years ago

1684838553 commented 2 years ago

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

示例 1:

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

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

来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/longest-palindromic-substring

1684838553 commented 2 years ago
/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {

    if(s.length <2){
        return s
    }

    let start = 0
    let maxLength = 1

    function getMaxLength(left,right){
        while(left>=0 && right<s.length && s[left] === s[right]){
            if(right - left + 1 > maxLength){
                maxLength = right - left + 1
                start = left
            }
            left--
            right++
        }
    }

    for(let i = 0;i<s.length;i++){
        getMaxLength(i-1,i+1)
        getMaxLength(i,i+1)
    }

    return s.substr(start,maxLength)
};