[LeetCode] 647. Palindromic Substrings

本文介绍了一种使用动态规划解决LeetCode上计数回文子串问题的方法。通过定义dp[i]为以第i个字符结尾的字符串中回文子串的数量,最终求和dp数组得到所有回文子串的总数。示例代码展示了如何实现这一算法。

题目内容

https://leetcode-cn.com/problems/palindromic-substrings/

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:

Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
 

Example 2:

Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

题目思路

这道题目我们可以使用动态规划的思想,dp[i]指以第i个字符为末尾的字符串包含多少回文子串,最后将dp的和返回。


程序代码

class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:return 0
        dp=[1]*len(s)
        for i in range(1,len(s)):
            for j in range(i-1,-1,-1):
                tmp=s[j:i+1]
                if tmp==tmp[::-1]:
                    dp[i]+=1
        return sum(dp)
                    
                    

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值