Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.html
Example 1:
Input:url
"bbbab"
Output:spa
4
One possible longest palindromic subsequence is "bbbb". .net
Example 2:
Input:code
"cbbd"
Output:htm
2
One possible longest palindromic subsequence is "bb".blog
給一個字符串,求最大的迴文子序列,子序列和子字符串不一樣,不須要是連續的字符。字符串
解法:DPget
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]。string
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 最長迴文子串