leetcode5. 最长回文子串

/**
 * @param {string} s
 * @return {string}
 */
var longestPalindrome = function(s) {
    let dp =[];
    let res = {};
    let len = s.length;
    for(let i=0;i<len;i++){
        dp.push([]);
        dp[i][i]=true;
        res['l'] = i;
        res['r'] = i;
    }
    for(let i=0;i<len;i++){
        if(len>1){
            dp[i][i+1]=s[i]==s[i+1]?true:false;
            if(dp[i][i+1]){
                res['l'] = i;
                res['r'] = i+1;
            }
        }
    }
    for(let size = 3;size<=len;size++){
        for(let l=0;l<len;l++){
            let r = l+size-1;
            if(r>=len){
                break;
            }
            if(s[l]!=s[r]){
                dp[l][r]=false;
            }else{
                dp[l][r] = dp[l+1][r-1]&&(s[l]==s[r]);
            }
            if(dp[l][r]){
                res['l'] = l;
                res['r'] = r;
            }
        }
    }
    return s.slice(res['l'],res['r']+1);
};

 

posted @ 2021-09-23 16:46  KYSpring  阅读(29)  评论(0编辑  收藏  举报