zoukankan      html  css  js  c++  java
  • LN : leetcode 516 Longest Palindromic Subsequence

    lc 516 Longest Palindromic Subsequence


    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 Accepted

    此问题是求最长回文子序列,和最长回文子串的区别在于序列可以是不连续的。dp[i][j]表示从i到j能生成的最长回文子序列的长度,由定义可知dp[i][i]肯定为1,并且当dp[i]等于dp[j]时,dp[i][j]=dp[i+1][j-1] + 2,否则,dp[i][j] = max(dp[i+1][j], dp[i][j-1])。

    class Solution {
    public:
        int longestPalindromeSubseq(string s) {
            int len = s.size();
            vector<vector<int>> dp(len, vector<int>(len));
            for (int i = len-1; i >= 0; i--) {
                dp[i][i] = 1;
                for (int j = i+1; j < len; 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][len-1];
        }
    };
    
  • 相关阅读:
    ubuntu使用iso作为本地源
    ubuntu配置简单的DNS服务器
    core data
    Core Animation教程
    制作framework&静态库
    notes
    textkit
    coretext
    nsset
    iOS Development Sites
  • 原文地址:https://www.cnblogs.com/renleimlj/p/8053932.html
Copyright © 2011-2022 走看看