Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

最长回文子序列 #419

Open
Pcjmy opened this issue Jan 22, 2023 · 1 comment
Open

最长回文子序列 #419

Pcjmy opened this issue Jan 22, 2023 · 1 comment

Comments

@Pcjmy
Copy link
Contributor

Pcjmy commented Jan 22, 2023

No description provided.

@Pcjmy
Copy link
Contributor Author

Pcjmy commented Feb 12, 2023

题目链接: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;
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant