516. Longest Palindromic Subsequence

来源:互联网 发布:阿里妈妈淘宝联盟推广 编辑:程序博客网 时间:2024/06/03 15:56

题目:

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".

思路:用动态规划的方法,令longest[i][j]表示字符串中从第i为到第j位的子字符串中最长的回文的长度,

if i==j longest[i][j] = 0;

if i+1 == j, then longest[i][j] = 2 if s[i] == s[j] longest[i][j] = 1

otherwise 

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

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

return longest[0][s.size()]

复杂度为O(n^2)

代码:

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

原创粉丝点击