问题描述:
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]; } };
有一维的解法:
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; }