DevPath

← All problems

Longest Palindromic Subsequence

Medium dynamic-programming · strings

Description

Return the length of the longest palindromic subsequence.

Constraints

1 <= length <= 1000

Examples

Input: s = "bbbab"

Output: 4

bbbb

Hints (1)
  • It equals the longest common subsequence of the string and its reverse.

Solutions

Interval DP in one row. · Time O(n^2) · Space O(n)

func longestPalindromeSubseq(s string) int {
    n := len(s)
    if n == 0 {
        return 0
    }
    dp := make([]int, n)
    for i := range dp {
        dp[i] = 1
    }
    for i := n - 1; i >= 0; i-- {
        prev := 0
        for j := i + 1; j < n; j++ {
            tmp := dp[j]
            if s[i] == s[j] {
                dp[j] = prev + 2
            } else if dp[j-1] > dp[j] {
                dp[j] = dp[j-1]
            }
            prev = tmp
        }
    }
    return dp[n-1]
}

Create a free account to submit solutions, track progress and save problems.

Create account