DEV Community

Abhishek Chaudhary
Abhishek Chaudhary

Posted on

1 1

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay