代码随想录训练营Day57| 647. 回文子串 516.最长回文子序列 动态规划总结篇

目录

学习目标

学习内容

 647. 回文子串  

  516.最长回文子序列


学习目标

  •  647. 回文子串  
  •  516.最长回文子序列
  •  动态规划总结篇

学习内容

 647. 回文子串  

647. 回文子串 - 力扣(LeetCode)icon-default.png?t=N4P3https://leetcode.cn/problems/palindromic-substrings/

class Solution:
    def countSubstrings(self, s: str) -> int:
        n = len(s)
        dp = [[0]*(n+1)for _ in range(n+1)]
        res = n
        for i in range(n,0,-1):
            for j in range(n+1):
                if i>=j:
                    dp[i][j]=1
                elif s[i-1]==s[j-1] and dp[i+1][j-1]:
                    dp[i][j]=1
                    res+=1
        #print(dp)
        return res
class Solution:
    def countSubstrings(self, s: str) -> int:
        n = len(s)
        res = 0
        for i in range(n):
            left = i-1
            right = i+1
            tmp = 1
            while left>-1 and right<n and s[left]==s[right]:
                tmp+=1
                left-=1
                right+=1
            res+=tmp
        for i in range(n-1):
            j=i+1
            left = i
            right = j
            tmp = 0
            while left>-1 and right<n and s[left]==s[right]:
                tmp+=1
                left-=1
                right+=1
            res+=tmp
        return res

  516.最长回文子序列

516. 最长回文子序列 - 力扣(LeetCode)icon-default.png?t=N4P3https://leetcode.cn/problems/longest-palindromic-subsequence/

class Solution:
    def longestPalindromeSubseq(self, s: str) -> int:
        n = len(s)
        dp = [[0]*(n+1)for _ in range(n+1)]
        for i in range(n,0,-1):
            for j in range(n+1):
                if i>j:continue
                elif i==j:dp[i][j]=1
                elif s[i-1]==s[j-1]:
                    dp[i][j]=dp[i+1][j-1]+2
                else:
                    dp[i][j]=max(dp[i+1][j],dp[i][j-1])
        #print(dp)
        return dp[1][n]
class Solution:
    def longestPalindromeSubseq(self, s: str) -> int:
        n = len(s)
        dp = [0]*(n+1)
        for i in range(n,0,-1):
            tmp = [0]*(n+1)
            for j in range(n+1):
                if i>j:continue
                elif i==j:tmp[j]=1
                elif s[i-1]==s[j-1]:
                    tmp[j]=dp[j-1]+2
                else:
                    tmp[j]=max(dp[j],tmp[j-1])
            dp = tmp
            #print(dp)
        return dp[n]

 problems/动态规划总结篇.md · programmercarl/leetcode-master(代码随想录出品) - Gitee.comicon-default.png?t=N4P3https://gitee.com/programmercarl/leetcode-master/blob/master/problems/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E6%80%BB%E7%BB%93%E7%AF%87.md

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值