给你一个字符串
s,请你统计并返回这个字符串中 回文子串 的数目。回文字符串 是正着读和倒过来读一样的字符串。
子字符串 是字符串中的由连续字符组成的一个序列。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的
输入:s = “abc”
输出:3
解释:三个回文子串: “a”, “b”, “c”
输入:s = “aaa”
输出:6
解释:6个回文子串: “a”, “a”, “a”, “aa”, “aa”, “aaa”
提示:
1 <= s.length <= 1000s由小写英文字母组成
1.确定dp数组(dp table)以及下标的含义
2.确定递推公式
3.dp数组如何初始化
4.确定遍历顺序
5.举例推导dp数组

基于回文字符串对称性的特点,我们可以采取从中心向两边扩展的方法,得到回文子串 :

当中心是 b 时,同时向左向右扩展一格,得到的子串为 aba,仍然符合回文的性质
继续向左向右扩展一格,得到的子串不符合回文的性质,停止!!
所以:以 b 为中心,可以得到的回文子串有两个 b 和 aba
但是,仅仅以单个字母为中心的方法会遗漏掉偶数回文子串的情况,如下图所示:

ng)]
所以我们不仅需要遍历以单个字母为中心的情况,也要遍历以两个字母为中心的情况
总结:「中心扩展法」的思想就是遍历以一个字符或两个字符为中心可得到的回文子串
class Solution:
def countSubstrings(self, s: str) -> int:
dp = [[False] * len(s) for _ in range(len(s))]
result = 0
for i in range(len(s)-1, -1, -1): #注意遍历顺序
for j in range(i, len(s)):
if s[i] == s[j] and (j - i <= 1 or dp[i+1][j-1]):
result += 1
dp[i][j] = True
return result
复杂度分析
- 时间复杂度:O(n^2)。
- 空间复杂度:O(n^2)。
class Solution:
def countSubstrings(self, s: str) -> int:
n = len(s)
result = 0
def helper(s: str, i: int, j: int):
nonlocal result
while i >= 0 and j < n and s[i] == s[j]:
i -= 1
j += 1
result += 1
for i in range(n):
# 以单个字母为中心的情况
helper(s, i, i)
# 以两个字母为中心的情况
helper(s, i, i + 1)
return result
复杂度分析
- 时间复杂度:O(n^2)。
- 空间复杂度:O(1)。
参考:https://leetcode.cn/problems/palindromic-substrings/solution/jian-dan-de-dong-tai-gui-hua-si-xiang-by-tinylife/