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]
相关推荐
ZTLJQ3 分钟前
基于机器学习的三国时期诸葛亮北伐失败因素量化分析
人工智能·算法·机器学习
JohnFF26 分钟前
48. 旋转图像
数据结构·算法·leetcode
bbc12122626 分钟前
AT_abc306_b [ABC306B] Base 2
算法
生锈的键盘34 分钟前
推荐算法实践:movielens数据集
算法
董董灿是个攻城狮35 分钟前
Transformer 通关秘籍9:词向量的数值实际上是特征
算法
林泽毅44 分钟前
SwanLab x EasyR1:多模态LLM强化学习后训练组合拳,让模型进化更高效
算法·llm·强化学习
小林熬夜学编程1 小时前
【高并发内存池】第八弹---脱离new的定长内存池与多线程malloc测试
c语言·开发语言·数据结构·c++·算法·哈希算法
余华余华1 小时前
2024年蓝桥杯Java B组省赛真题超详解析-分布式队列
java·职场和发展·蓝桥杯
刚入门的大一新生1 小时前
归并排序延伸-非递归版本
算法·排序算法
独好紫罗兰1 小时前
洛谷题单3-P1980 [NOIP 2013 普及组] 计数问题-python-流程图重构
开发语言·python·算法