[LeetCode] 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
State: dp[i][j], 表示[i,j]区间内的字符串的最长回文子序列。如果s[i]==s[j],那么i和j就可以增加2个回文串的长度,我们知道中间dp[i + 1][j - 1]的值,那么其加上2就是dp[i][j]的值。如果s[i] != s[j],那么我们可以去掉i或j其中的一个字符,然后比较两种情况下所剩的字符串谁dp值大,就赋给dp[i][j]。
Function: dp[i][j] = dp[i + 1][j - 1] + 2 if (s[i] == s[j]) or max(dp[i + 1][j], dp[i][j - 1]) if (s[i] != s[j])
C++: dp[i][j]
class Solution { public: int longestPalindromeSubseq(string s) { int n = s.size(); vector<vector<int>> dp(n, vector<int>(n)); for (int i = n - 1; i >= 0; --i) { dp[i][i] = 1; for (int j = i + 1; j < n; ++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][n - 1]; } };
C++: dp[i]
class Solution { public: int longestPalindromeSubseq(string s) { int n = s.size(), res = 0; vector<int> dp(n, 1); for (int i = n - 1; i >= 0; --i) { int len = 0; for (int j = i + 1; j < n; ++j) { int t = dp[j]; if (s[i] == s[j]) { dp[j] = len + 2; } len = max(len, t); } } for (int num : dp) res = max(res, num); return res; } };
类似题目:
[LeetCode] 125. Valid Palindrome 有效回文
[LeetCode] 9. Palindrome Number 验证回文数字
[LeetCode] 5. Longest Palindromic Substring 最长回文子串