![]() |
VOOZH | about |
Given a string s, return the length of the longest good palindromic subsequence in s such that:
Example:
Input: s = "bbabab"
Output: 4
Explanation: The longest good palindromic subsequence of s is "baab".Input: s = "dcbccacdb"
Output: 4
Explanation: The longest good palindromic subsequence of s is "dccd"
Approach:
Uses a dynamic programming approach. We'll use 2D vector of pairs dp[i][j] to store the length of the longest good palindromic subsequence and the last character of the subsequence for each substring s[i, j] of the given string.
Iterate over each substring of the given string in reverse order. For each substring, compare the characters at the left and right ends.
Case 1:Characters at Ends are Equal: If the characters at the left and right ends of the substring are the same and are not the same as the last character of the longest good palindromic subsequence of the substring excluding the left and right ends, then extend the subsequence by adding the characters at the left and right ends. This is because adding the characters at the ends will form a longer good palindromic subsequence.
Case 2: Characters at ends are Not Equal or Same as Last Character of Subsequence: If the characters at the ends are not equal or are the same as the last character of the subsequence, then the longest good palindromic subsequence of the current substring is the longer one between the subsequences of the substrings excluding the left end and excluding the right end. This is because adding either character at the ends will not form a good palindromic subsequence.
After iterating over all substrings, return the length of the longest good palindromic subsequence of the given string, which is stored in dp[0][n - 1].first
Step-by-step approach:
Below is the implementation of the above approach:
The length of the longest good palindromic subsequence in "abcabcabb" is 4.
Time Complexity: O(n^2)
Auxiliary Space: O(n^2)