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> dp(len, vector(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];
}
};

posted @ 2018-01-09 15:59  三石宝宝  阅读(176)  评论(0)    收藏  举报