Algo-Sim › Dynamic Programming
Longest Palindromic Subsequence
Medium · Dynamic Programming · step through it in Java, Python and C++ on your own input
Interval DP over s[i..j]: matching ends add 2 to the inside, otherwise drop one end. It equals the LCS of s and its reverse.
Problem
Given a string s, return the length of its longest palindromic subsequence: the longest palindrome you can get by deleting some characters (possibly none) without reordering the rest.
Constraints
- 1 ≤ s.length ≤ 1000
- s has only lowercase English letters
Edge cases to test
- One character
- No repeated letters:
1 - The whole string is a palindrome
Follow-up questions
- Why does it equal LCS(s, reverse(s))?
- A common subsequence of s and its reverse reads the same both ways, and the longest one is a palindrome.
- What uses it?
- The fewest insertions or deletions to make s a palindrome is n − LPS (LC 1312).
Solution
Java
public int longestPalindromeSubseq(String s) {
int n = s.length();
int[][] dp = new int[n][n];
for (int i = n - 1; i >= 0; i--) {
dp[i][i] = 1;
for (int j = i + 1; j < n; j++) {
if (s.charAt(i) == s.charAt(j)) dp[i][j] = dp[i + 1][j - 1] + 2;
else dp[i][j] = Math.max(dp[i + 1][j], dp[i][j - 1]);
}
}
return dp[0][n - 1];
}Python
def longest_palindrome_subseq(s):
n = len(s)
dp = [[0] * n for _ in range(n)]
for i in range(n - 1, -1, -1):
dp[i][i] = 1
for j in range(i + 1, n):
if s[i] == s[j]: dp[i][j] = dp[i + 1][j - 1] + 2
else: dp[i][j] = max(dp[i + 1][j], dp[i][j - 1])
return dp[0][n - 1]C++
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int longestPalindromeSubseq(string &s) {
int n = int(s.size());
vector<vector<int>> dp(n, vector<int>(n));
for (int i = n - 1; i >= 0; i--) {
dp[i][i] = 1;
for (int j = i + 1; j < n; j++) {
if (s[i] == s[j]) dp[i][j] = dp[i + 1][j - 1] + 2;
else dp[i][j] = max(dp[i + 1][j], dp[i][j - 1]);
}
}
return dp[0][n - 1];
}
};
More Dynamic Programming problems
- Climbing Stairs: Recursion → Memo → Table (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Perfect Squares (Medium)
- Combination Sum IV (Medium)
- Decode Ways (Medium)
- Maximum Product Subarray (Medium)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Best Time to Buy and Sell Stock with Transaction Fee (Medium)
- Best Time to Buy and Sell Stock III (Hard)
- Longest Increasing Subsequence (Medium)
- Word Break (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Maximal Square (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Longest Common Subsequence (Medium)
- Interleaving String (Medium)
- 0/1 Knapsack (Medium)
- Edit Distance (Medium)
- Distinct Subsequences (Hard)
- Longest Palindromic Substring (Medium)
- Palindromic Substrings (Medium)
- Predict the Winner (Medium)
- Stone Game (Medium)