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]
相关推荐
万岳科技系统开发1 天前
外卖小程序中的高并发处理:如何应对大流量订单的挑战
算法·小程序·开源
TL滕1 天前
从0开始学算法——第二天(时间、空间复杂度)
数据结构·笔记·学习·算法
weixin_441003641 天前
2025教资面试真题电子版|科目试讲+结构化真题解析|完整PDF
面试·职场和发展·pdf
程序员三藏1 天前
Postman接口测试详解
自动化测试·软件测试·python·测试工具·职场和发展·接口测试·postman
旺仔老馒头.1 天前
【数据结构与算法】手撕排序算法(二)
c语言·数据结构·算法·排序算法
好学且牛逼的马1 天前
【Hot100 | 2 LeetCode49 字母异位词分组问题】
算法
2301_795167201 天前
Rust 在内存安全方面的设计方案的核心思想是“共享不可变,可变不共享”
算法·安全·rust
czhc11400756631 天前
Java117 最长公共前缀
java·数据结构·算法
java 乐山1 天前
蓝牙网关(备份)
linux·网络·算法
云泽8081 天前
快速排序算法详解:hoare、挖坑法、lomuto前后指针与非递归实现
算法·排序算法