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:
4One possible longest palindromic subsequence is "bbbb".
Example 2: Input:
"cbbd"Output:
2One possible longest palindromic subsequence is "bb".
// Bottom-Up Dynamic Programming
int longestPalindromeSubseq(string s) { // time: O(n^2); space: O(n^2)
int n = s.size();
vector<vector<int> > dp(n, vector<int>(n, 0));
for (int j = 0; j < n; ++j) {
dp[j][j] = 1;
for (int i = j - 1; i >= 0; --i) {
if (s[i] == s[j]) {
dp[i][j] = (j - i >= 2 ? dp[i + 1][j - 1] : 0) + 2;
} else {
dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
}
}
return dp[0][n - 1];
}Last updated
Was this helpful?