LeetCode 516: Longest Palindromic Subsequence
Problem Description
Explanation
To find the longest palindromic subsequence in a given string, we can use dynamic programming. We will create a 2D array dp
to store the lengths of the longest palindromic subsequence for each substring. The base case would be when the length of the substring is 1, in which case the longest palindromic subsequence length would be 1.
We iterate through the string s
and fill the dp
array based on the following cases:
- If
s[i] == s[j]
, we can include both characters in the palindromic subsequence, so we add 2 to the length of the palindromic subsequence ending ati
andj
. - If
s[i] != s[j]
, we take the maximum of the length of the palindromic subsequence ending ati-1
andj
ori
andj-1
.
The final answer will be stored in dp[0][n-1]
, where n
is the length of the input string.
Time Complexity: O(n^2), where n is the length of the input string. Space Complexity: O(n^2), where n is the length of the input string.
Solutions
class Solution {
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];
}
}
Related LeetCode Problems
Loading editor...