Leetcode 647.回文子串
1 题目描述(Leetcode题目链接)
给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。
输入: "abc"
输出: 3
解释: 三个回文子串: "a", "b", "c".
输入: "aaa"
输出: 6
说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".
注:输入的字符串长度不会超过1000。
2 题解
本题与最长回文子串很类似, D P DP DP的定义稍有不同,这次定义为 D P [ i ] [ j ] DP[i][j] DP[i][j]表示 i i i到 j j j的子串是否为回文子串,因此只取1或0,详细的状态转移方程参考最长回文子串即可。
class Solution:
def countSubstrings(self, s: str) -> int:
length = len(s)
DP = [([1]*length) for _ in range(length)]
retv = length
for i in range(length-2, -1, -1):
for j in range(i+1, length):
if s[i] == s[j] and DP[i+1][j-1] == 1:
DP[i][j] = 1
retv += 1
else:
DP[i][j] = 0
return retv
可以优化一下空间复杂度,由于是上三角或下三角矩阵,所以用一维数组来存就可以了。
class Solution:
def countSubstrings(self, s: str) -> int:
length = len(s)
DP = [0]*length
retv = 0
for i in range(length):
DP[i] = 1
retv += 1
for j in range(i):
if s[i] == s[j] and DP[j+1] == 1:
DP[j] = 1
retv += 1
else:
DP[j] = 0
return retv