Skip to content

516. Longest Palindromic Subsequence

MediumLeetCode

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.

How to solve the problem

  • Dynamic Programming
python
class Solution:
    def longestPalindromeSubseq(self, s: str) -> int:
        n = len(s)

        @cache
        def dfs(i, j):
            if i > j:
                return 0  # empty substring
            if i == j:
                return 1  # single character
            if s[i] == s[j]:
                return dfs(i + 1, j - 1) + 2  # match: extend by 2
            return max(dfs(i + 1, j), dfs(i, j - 1))  # skip left or right

        return dfs(0, n - 1)

Complexity

  • Time complexity: O(n^2)
  • Space complexity: O(n^2)

Comments

No comments yet. Be the first to comment!