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:
4One possible longest palindromic subsequence is "bbbb".
Example 2:
Input:
"cbbd"Output:
2
One possible longest palindromic subsequence is "bb".
class Solution {
public:
int longestPalindromeSubseq(string s) {
int len = s.length();
vector<vector<int> > dp(len, vector<int>(len, 0));
for(int i = 0; i < len; i++)
dp[i][i] = 1;
for(int i = 0; i < len - 1; i++){
if(s[i] == s[i + 1])
dp[i][i + 1] = 2;
else
dp[i][i + 1] = 1;
}
for(int l = 3; l <= len; l++){
for(int j = 0; j < len - l + 1; j++){
int k = j + l - 1;
if(s[j] == s[k])
dp[j][k] = 2 + dp[j + 1][k - 1];
else
dp[j][k] = max(dp[j][k - 1], dp[j + 1][k]);
}
}
return dp[0][len - 1];
}
};