Longest Palindromic Subsequence II Problem
Description
LeetCode Problem 1682.
A subsequence of a string s is considered a good palindromic subsequence if:
- It is a subsequence of
s. - It is a palindrome (has the same value if reversed).
- It has an even length.
- No two consecutive characters are equal, except the two middle ones.
For example, if s = "abcabcabb", then "abba" is considered a good palindromic subsequence, while "bcb" (not even length) and "bbbb" (has equal consecutive characters) are not.
Given a string s, return the length of the longest good palindromic subsequence in s.
Example 1:
Input: s = "bbabab"
Output: 4
Explanation: The longest good palindromic subsequence of s is "baab".
Example 2:
Input: s = "dcbccacdb"
Output: 4
Explanation: The longest good palindromic subsequence of s is "dccd".
Constraints:
1 <= s.length <= 250sconsists of lowercase English letters.
Solution
Approach: Memoized Search With the Last Letter Used
A good palindrome is built from the outside in, one matching pair at a time, and two neighbouring pairs must use different letters. So when we choose a pair inside s[i..j], we need to know which letter the enclosing pair used.
Let dfs(i, j, x) be the length of the longest good palindromic subsequence inside s[i..j] whose outer pair is not the letter x (x = 26 means "no enclosing pair yet"). The answer is dfs(0, n - 1, 26).
- If
i >= j, nothing fits: return0. - If
s[i] == s[j]and that letter is notx, use them as the outer pair:dfs(i + 1, j - 1, s[i]) + 2. Taking this pair is never worse than skipping it. - Otherwise drop one end:
max(dfs(i + 1, j, x), dfs(i, j - 1, x)).
Memoize the results so every state is computed once.
Complexity: O(n2 * C) time and space, where C = 26 is the alphabet size.
from functools import lru_cache
class Solution:
def longestPalindromeSubseq(self, s: str) -> int:
@lru_cache(None)
def dfs(i, j, x):
if i >= j:
return 0
if s[i] == s[j] and s[i] != x:
return dfs(i + 1, j - 1, s[i]) + 2
return max(dfs(i + 1, j, x), dfs(i, j - 1, x))
ans = dfs(0, len(s) - 1, '')
dfs.cache_clear()
return ans