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]
相关推荐
forestsea1 分钟前
现代 JavaScript 加密技术详解:Web Crypto API 与常见算法实践
前端·javascript·算法
张洪权5 分钟前
bcrypt 加密
算法
快手技术13 分钟前
视频理解霸榜!快手 Keye-VL 旗舰模型重磅开源,多模态视频感知领头羊
算法
骑自行车的码农1 小时前
🍂 React DOM树的构建原理和算法
javascript·算法·react.js
CoderYanger2 小时前
优选算法-优先级队列(堆):75.数据流中的第K大元素
java·开发语言·算法·leetcode·职场和发展·1024程序员节
希望有朝一日能如愿以偿2 小时前
力扣每日一题:能被k整除的最小整数
数据结构·算法·leetcode
Controller-Inversion2 小时前
力扣53最大字数组和
算法·leetcode·职场和发展
rit84324992 小时前
基于感知节点误差的TDOA定位算法
算法
m0_372257022 小时前
ID3 算法为什么可以用来优化决策树
算法·决策树·机器学习
q***25212 小时前
SpringMVC 请求参数接收
前端·javascript·算法