题目内容
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)

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

286

被折叠的 条评论
为什么被折叠?



