DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

Longest Palindromic Subsequence

Given a string s, find the longest palindromic subsequence's length in s.

A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.

Example 1:

Input: s = "bbbab"
Output: 4
Explanation: One possible longest palindromic subsequence is "bbbb".

Example 2:

Input: s = "cbbd"
Output: 2
Explanation: One possible longest palindromic subsequence is "bb".

Constraints:

  • 1 <= s.length <= 1000
  • s consists only of lowercase English letters.

SOLUTION:

class Solution:
    cache = {}

    def maxPalindrome(self, s, i, j):
        key = 1100 * i + j
        if (key) in self.cache:
            return self.cache[key]
        if i == j:
            self.cache[key] = 1
        elif s[i] == s[j] and i + 1 == j:
            self.cache[key] = 2
        elif s[i] == s[j]:
            self.cache[key] = self.maxPalindrome(s, i + 1, j - 1) + 2
        else:
            self.cache[key] = max(self.maxPalindrome(s, i, j - 1), self.maxPalindrome(s, i + 1, j))
        return self.cache[key]

    def longestPalindromeSubseq(self, s: str) -> int:
        self.cache.clear()
        return self.maxPalindrome(s, 0, len(s) - 1)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)