LeetCode 1682: Longest Palindromic Subsequence II Solution
Master LeetCode problem 1682 (Longest Palindromic Subsequence II), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1682. Longest Palindromic Subsequence II
Problem Explanation
Explanation:
This problem asks us to find the length of the longest palindromic subsequence possible after deleting at most one character from the original string.
To solve this problem, we can use dynamic programming. We will maintain a 2D array dp to store the longest palindromic subsequence length for each substring. We will iterate over all possible substrings and compute the longest palindromic subsequence length for each of them.
If the characters at the start and end of the current substring are the same, we can include both characters in the palindromic subsequence. Otherwise, we have two options: either exclude the character at the start or exclude the character at the end to maximize the length of the palindromic subsequence.
We will build the dp array using this logic and finally return the maximum palindromic subsequence length after deleting at most one character.
:
Solution Code
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]);
}
}
}
int maxLength = 0;
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
int currLength = dp[i][j];
if (i > 0 && j < n - 1 && s.charAt(i - 1) == s.charAt(j + 1)) {
currLength += 1;
}
maxLength = Math.max(maxLength, currLength);
}
}
return maxLength;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1682 (Longest Palindromic Subsequence II)?
This page provides optimized solutions for LeetCode problem 1682 (Longest Palindromic Subsequence II) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1682 (Longest Palindromic Subsequence II)?
The time complexity for LeetCode 1682 (Longest Palindromic Subsequence II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1682 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1682 in Java, C++, or Python.