Leetcode 516. Longest Palindromic Subsequence
Given a string s
, find the longest palindromic subsequence’s length in s
. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.
s = "bbbab"
4
n
)?
We need to find the longest palindromic subsequence. This can be achieved using dynamic programming. Here’s the approach:
Define a DP Table:
Let dp[i][j]
represent the length of the longest palindromic subsequence within the substring s[i:j+1]
.
i == j
, the length is 1
because a single character is a palindrome.i > j
, this doesn’t make sense in our context since it represents an invalid range.s[i] == s[j]
, then dp[i][j] = 2 + dp[i+1][j-1]
.s[i] != s[j]
, then dp[i][j] = max(dp[i+1][j], dp[i][j-1])
.dp[0][n-1]
which includes the entire string.#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int longestPalindromeSubseq(string s) {
int n = s.size();
if (n == 0) return 0;
vector<vector<int>> dp(n, vector<int>(n, 0));
// Base cases: A single character is a palindrome of length 1
for (int i = 0; i < n; ++i) {
dp[i][i] = 1;
}
// Fill the table
for (int len = 2; len <= n; ++len) { // starting from length 2 to n
for (int i = 0; i <= n - len; ++i) {
int j = i + len - 1;
if (s[i] == s[j]) {
dp[i][j] = 2 + dp[i+1][j-1];
} else {
dp[i][j] = max(dp[i+1][j], dp[i][j-1]);
}
}
}
// The result is in dp[0][n-1]
return dp[0][n-1];
}
This solution is optimal for the constraints typically provided in competitive programming and interviews.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?