516. Longest Palindromic Subsequence (DP)

Here we have two solutions.

Both are DP.

The first solution is quite smart and difficult to think of.

Basically, you just need to reverse the string, and then find the longest common subsequence.

The reason is a palindromic string is the same as it is reversed. So, we just need to reverse the string and find the longest common subsequence that is the answer we needed.

class Solution {
public:
    int longestCommonSubsequence(string &a, string &b) {
        short m[2][10000] = {};
        for (int i = 0; i < a.size(); ++i)
            for (int j = 0; j < b.size(); ++j)
                m[!(i % 2)][j + 1] = a[i] == b[j] ? m[i % 2][j] + 1 : max(m[i % 2][j + 1], m[!(i % 2)][j]);
        return m[a.size() % 2][b.size()];
    }
    int longestPalindromeSubseq(string s) {
        string x = s;
        reverse(s.begin(), s.end());
        return longestCommonSubsequence(x, s);
    }
};

The second method is quite intuitive.  We consider the DP array as a certain interval that has the longest palindrome. 

DP[i][j] represents the longest length of the palindrome subsequence between intervals i to j.

The equation is easy to think of because the larger interval relies on the smaller interval which is dp[i + 1][j - 1].

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
>