Longest Palindromic Subsequence

Posted xpp

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Longest Palindromic Subsequence相关的知识,希望对你有一定的参考价值。

 方法:与substring的不同是这里不需要子串连续

class Solution {
public:
    int longestPalindromeSubseq(string s) {
        vector<vector<int>> f(s.size(), vector<int>(s.size(), 0));
        
        for(int i=s.size()-1; i>=0; --i)
        {
            f[i][i] = 1;
            for(int j=i+1; j<s.size(); ++j)
            {
                if(s[i] == s[j])
                    f[i][j] = f[i+1][j-1] + 2;
                else
                    f[i][j] = max(f[i+1][j], f[i][j-1]);
            }
        }
        
        return f[0][s.size()-1];
    }
};

或者

class Solution {
public:
    int longestPalindromeSubseq(string s) {
        vector<vector<int>> f(s.size(), vector<int>(s.size(), 0));
        
        for(int i=0; i<s.size(); ++i)
        {
            f[i][i] = 1;
            for(int j=i-1; j>=0; --j)
            {
                if(s[i] == s[j])
                    f[j][i] = f[j+1][i-1] + 2;
                else
                    f[j][i] = max(f[j+1][i], f[j][i-1]);
            }
        }
        
        return f[0][s.size()-1];
    }
};

 

以上是关于Longest Palindromic Subsequence的主要内容,如果未能解决你的问题,请参考以下文章

leedcode Longest Palindromic Substring

5. Longest Palindromic Substring

[Leetcode]Longest Palindromic Substring

LeetCode:Longest Palindromic Substring

leetcode--5. Longest Palindromic Substring

#Leetcode# 5. Longest Palindromic Substring