Leetcode- Longest Palindromic Subsequence

来源:互联网 发布:淘宝联盟不返利 编辑:程序博客网 时间:2024/06/15 16:55

Problem

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

具体详见Leetcode

Analysis

首先明确这道题是判断回文子序列的最大长度,而不是回文子串,所以不要求能够出现连续的回文字符串。所以,可以使用动态规划方程。
算法:把字符串s反转成新的字符串s1,判断字符串s和字符串s1之间的最长的子序列长度。这个长度就是最长的回文子序列长度。
f[i][j]表示字符串s[0…i-1]和字符串s1[0…j-1]最长的相同子序列。
f[i][j]是在三个选择中选择最大的那个。第一个选择是来源于f[i1][j1]+isSameOrNot如果s[i1]==s1[j1],isSameOrNot为1,加上后就是相同子序列长度加一,不相等的话就为0,和f[i1][j1]长度相等。第二个选择是f[i1][j],第三个选择是f[i][j1],第二种和第三种是去掉s[i1]或者s1[j1]的子问题,说明被去掉的字符对子序列没有作用。
在这三种选择中选值最大的情况。
所以,状态转移方程为:
f[i][j]=max{f[i1][j1]+same,f[i1][j],f[i][j1]}1<=i,j<=s.size()

Complexity

时间复杂度:O(n2)
空间复杂度:O(n2)

Code

class Solution {public:    int longestPalindromeSubseq(string s) {        int m = s.size();        int** matrix = new int*[m+1];        for (int i = 0; i <= m; i++)            matrix[i] = new int[m+1];        for(int i = 0; i <= m; i++) {            matrix[0][i] = 0;            matrix[i][0] = 0;        }        for (int i = 1; i <= m; i++) {            for (int j = 1; j <= m; j++) {                int same = (s[i-1] == s[m-j]) ? 1 : 0;                matrix[i][j] = max(matrix[i-1][j-1]+same,matrix[i-1][j]);                matrix[i][j] = max(matrix[i][j],matrix[i][j-1]);            }        }        int result = matrix[s.size()][s.size()];        for (int i = 0; i <= m; i++)            delete []matrix[i];        delete []matrix;        return result;    }};
原创粉丝点击