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 sleft...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 } sleft == sright \\ \maxf(left+1, right), f(left, right-1) & \text{otherwise} \end{cases} f(left,right)={f(left+1,right−1)+2maxf(left+1,right),f(left,right−1)if sleft==srightotherwise

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]
相关推荐
浅念-4 分钟前
动态规划:线性DP——多状态DP与子数组专题笔记
c++·笔记·算法·leetcode·职场和发展·动态规划·力扣
Data analyse45616 分钟前
rrweb回放事件资源加载顺序重放校验
前端·人工智能·算法·机器学习·数据分析
昨夜见军贴061620 分钟前
原始采样记录数字化落地,IACheck AI 报告文档审核 Agent 实现监测文档校验自动化
人工智能·算法·自动化
微学AI34 分钟前
从历史曲线到提前预警:TimechoAI 的时序预测与业务落地实践
人工智能·算法
不会就选b1 小时前
算法日常・每日刷题--<动态规划>26
算法·动态规划
荆棘鸟智能1 小时前
虫情测报灯图像识别算法实践:小目标检测、粘连计数与飞虱细粒度分类
算法·目标检测·分类
学电子她就能回来吗1 小时前
LeetCode Hot 100|滑动窗口专题零基础学习笔记
笔记·学习·leetcode
天真小巫1 小时前
2026.10.14总结
职场和发展
鸥梨菌Honevid1 小时前
UVM 面试高频:uvm_test_top 与 uvm_config_db 路径机制全解析
数据库·面试·职场和发展
爱读书的小胖2 小时前
LeetCode 27. 移除元素(C)解题分析
数据结构·算法