516. Longest Palindromic Subsequence

问题描述:

Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.

Example 1:
Input:

"bbbab"

Output:

4

One possible longest palindromic subsequence is "bbbb".

 

Example 2:
Input:

"cbbd"

Output:

2

One possible longest palindromic subsequence is "bb".

 

解题思路:

这道题可以想到用dp来解,而且是二维dp

dp[i][j]的含义为:字符串s的子串[i,j]中可以构成的最长回文序列的长度。

状态转移方程为:

dp[i][j] = dp[i+1][j-1] if(s[i] == s[j] && i != j-1)

dp[i][j] = 2 if(s[i] == s[j] && i == j-1)

dp[i][j] = max(dp[i+1][j], dp[i][j-1])

 

代码:

时间复杂度为O(n2)

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

 

有一维的解法:

参考:https://leetcode.com/problems/longest-palindromic-subsequence/discuss/146968/C++-DP-with-1D-array-8ms-beats-100

class Solution {
public:
    int longestPalindromeSubseq(string s);
};

int Solution::longestPalindromeSubseq(string s){
    if(s.empty())
        return 0;
    int len = s.size();
    vector<int> dp(len, 1);   
    for (int i=1; i<len; ++i){
        int maxlen = 0;
        for (int j=i-1; j>=0; --j){
            int previous_max = maxlen;
            if (dp[j]>maxlen)
                maxlen = dp[j];
            if(s[j]==s[i]){
                dp[j] = previous_max + 2; // update
            }
        }
    }
    int maxlen = 1;
    int i=0;
    while(i<len){
        maxlen = max(maxlen, dp[i]);
        i++;
    }
    
    return maxlen;
}

 

转载于:https://www.cnblogs.com/yaoyudadudu/p/9425336.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值