1 题目
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".
2 尝试解
2.1 分析
给定一个字符串,求其最长回文子序列(子序列不要求连续),与最长连续公共子序列动态递归思路相似。
longest-palindrome(s,i,j)
s[i]==s[j] : longest-palindrome(s,i,j) = 2 + longest-palindrome(s,i+1,j-1)
s[i]!=s[j] : longest-palindrome(s,i,j) = max(longest-palindrome(s,i+1,j),longest-palindrome(s,i,j-1))
或者直接将字符串翻转,求最长公共子序列。
2.2 代码
class Solution {
public:
int longestPalindromeSubseq(string s) {
vector<vector<int>> record(s.size(),vector<int>(s.size(),-1));
return longest_palindrome_aux(s,0,s.size()-1,record);
}
int longest_palindrome_aux(string&s,int i, int j, vector<vector<int>>&record){
if(record[i][j] >= 0) return record[i][j];
int result = 0;
if(i == j) result = 1;
else if(i > j) result = 0;
else{
if(s[i]==s[j])
result = 2 + longest_palindrome_aux(s,i+1,j-1,record);
else
result = max(longest_palindrome_aux(s,i+1,j,record),longest_palindrome_aux(s,i,j-1,record));
}
record[i][j] = result;
return result;
}
};
3 标准解
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;
}
};