问题描述:
Given a string s, find the longest palindromic subsequence's length in s. You may assume that the maximum length of s is 1000.
示例:
Input:
"bbbab"Output:
4One possible longest palindromic subsequence is "bbbb".
Input:
"cbbd"Output:
2One possible longest palindromic subsequence is "bb".
问题分析:
我们可以采用动态规划算法实现,设置状态转移数组dp[i][j]表示索引i到j中的最长回文的字符串元素个数。
过程详见代码:
class Solution {
public:
int longestPalindromeSubseq(string s) {
int n = s.length();
vector<vector<int>> dp(n, vector<int>(n, 1));
for (int i = n - 1; i >= 0 ; i--)
{
for (int j = i + 1; j < n; j++)
{
if (s[i] == s[j])
{
if (i + 2 <= j)
dp[i][j] = dp[i + 1][j - 1] + 2;
else dp[i][j] = 2;
}
else dp[i][j] = max(dp[i][j - 1], dp[i + 1][j]);
}
}
return dp[0][n - 1];
}
};