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]
相关推荐
TracyCoder1233 小时前
LeetCode Hot100(15/100)——54. 螺旋矩阵
算法·leetcode·矩阵
u0109272714 小时前
C++中的策略模式变体
开发语言·c++·算法
2501_941837265 小时前
停车场车辆检测与识别系统-YOLOv26算法改进与应用分析
算法·yolo
六义义6 小时前
java基础十二
java·数据结构·算法
四维碎片6 小时前
QSettings + INI 笔记
笔记·qt·算法
Tansmjs6 小时前
C++与GPU计算(CUDA)
开发语言·c++·算法
独自破碎E7 小时前
【优先级队列】主持人调度(二)
算法
weixin_445476687 小时前
leetCode每日一题——边反转的最小成本
算法·leetcode·职场和发展
打工的小王7 小时前
LeetCode Hot100(一)二分查找
算法·leetcode·职场和发展
Swift社区7 小时前
LeetCode 385 迷你语法分析器
算法·leetcode·职场和发展