Leetcode 516. Longest Palindromic Subsequence

Problem

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.

Algorithm

Dynamic Programming (DP). Define state f(left, right) is the Longest Palindromic Subsequence in s[left...right], so we have
f ( l e f t , r i g h t ) = { f ( l e f t + 1 , r i g h t − 1 ) + 2 if s [ l e f t ] = = s [ r i g h t ] max ⁡ [ f ( l e f t + 1 , r i g h t ) , f ( l e f t , r i g h t − 1 ) ] otherwise f(left, right) = \begin{cases} f(left+1, right-1) + 2 & \text{if } s[left] == s[right ]\\ \max[f(left+1, right), f(left, right-1)] & \text{otherwise} \end{cases} f(left,right)={f(left+1,right−1)+2max[f(left+1,right),f(left,right−1)]if s[left]==s[right]otherwise

Code

python3 复制代码
class Solution:
    def longestPalindromeSubseq(self, s: str) -> int:
        slen = len(s)
        if slen == 0:
            return 0
        
        dp = [[0] * slen for i in range(slen)]
        for i in range(slen):
            dp[i][i] = 1
        for L in range(2, slen+1):
            for i in range(slen - L + 1):
                j = i + L - 1
                if s[i] == s[j]:
                    dp[i][j] = dp[i+1][j-1] + 2
                else:
                    dp[i][j] = max(dp[i+1][j], dp[i][j-1])

        return dp[0][slen-1]
相关推荐
fai厅的秃头姐!2 小时前
C语言03
c语言·数据结构·算法
lisanndesu2 小时前
动态规划
算法·动态规划
myprogramc3 小时前
十大排序算法
数据结构·算法·排序算法
记得早睡~3 小时前
leetcode150-逆波兰表达式求值
javascript·算法·leetcode
修己xj3 小时前
算法系列之贪心算法
算法
qy发大财3 小时前
跳跃游戏(力扣55)
算法·leetcode
BingLin-Liu3 小时前
蓝桥杯备考:搜索算法之排列问题
算法·职场和发展·蓝桥杯
计算机小白一个3 小时前
蓝桥杯 Java B 组之岛屿数量、二叉树路径和(区分DFS与回溯)
java·数据结构·算法·蓝桥杯
curemoon4 小时前
理解都远正态分布中指数项的精度矩阵(协方差逆矩阵)
人工智能·算法·矩阵
柃歌4 小时前
【UCB CS 61B SP24】Lecture 7 - Lists 4: Arrays and Lists学习笔记
java·数据结构·笔记·学习·算法