Sunny-117 / js-challenges

✨✨✨ Challenge your JavaScript programming limits step by step

Home Page:https://juejin.cn/column/7244788137410560055

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

最长回文子序列

Pcjmy opened this issue · comments

commented
最长回文子序列
commented

题目链接:https://leetcode.cn/problems/longest-palindromic-subsequence/description
时间复杂度:O(n^2)
解题思路:问题等价于求原串和反串的最长公共子序列

/**
 * @param {string} s
 * @return {number}
 */
var longestPalindromeSubseq = function(s) {
    let ans=0;
    let n=s.length;
    let f=new Array(n).fill(0).map(() => new Array(n).fill(0));
    let t=s.split('').reverse().join('');
    for(let i=0;i<n;i++)
    {
        for(let j=0;j<n;j++)
        {
            if(i>0) f[i][j]=Math.max(f[i][j],f[i-1][j]);
            if(j>0) f[i][j]=Math.max(f[i][j],f[i][j-1]);
            if(s[i]===t[j]&&i>0&&j>0) f[i][j]=Math.max(f[i][j],f[i-1][j-1]+1);
            if((!i||!j)&&s[i]===t[j]) f[i][j]=1;
        }
    }
    for(let i=0;i<n;i++)
    {
        for(let j=0;j<n;j++)
        {
            ans=Math.max(ans,f[i][j]);
        }
    }
    return ans;
};