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]
相关推荐
长安——归故李22 分钟前
【modbus学习】
java·c语言·c++·学习·算法·c#
兴科Sinco1 小时前
[leetcode 1]给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出和为目标值 target 的那两个整数[力扣]
python·算法·leetcode
沐怡旸1 小时前
【算法--链表】138.随机链表的复制--通俗讲解
算法·面试
anlogic1 小时前
Java基础 9.10
java·开发语言·算法
薛定谔的算法1 小时前
JavaScript单链表实现详解:从基础到实践
数据结构·算法·leetcode
CoovallyAIHub1 小时前
CostFilter-AD:用“匹配代价过滤”刷新工业质检异常检测新高度! (附论文和源码)
深度学习·算法·计算机视觉
幻奏岚音1 小时前
《数据库系统概论》第一章 初识数据库
数据库·算法·oracle
你好,我叫C小白1 小时前
贪心算法(最优装载问题)
算法·贪心算法·最优装载问题
CoovallyAIHub1 小时前
CVPR 2025 | 频率动态卷积(FDConv):以固定参数预算实现频率域自适应,显著提升视觉任务性能
深度学习·算法·计算机视觉
mit6.8241 小时前
[rStar] 解决方案节点 | `BaseNode` | `MCTSNode`
人工智能·python·算法