题目
给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。
示例 1:
输入: "abc"
输出: 3
解释: 三个回文子串: "a", "b", "c".
示例 2:
输入: "aaa"
输出: 6
说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".
注意:
输入的字符串长度不会超过1000。
解题思路
暴力,对每个位置都检查包含了该位置后,向后有几个字符能组成回文串。暴力遍历的时间复杂度是 o ( n 2 ) o(n^2) o(n2),检查回文串的时间复杂度是 o ( n ) o(n) o(n),总共复杂度是 o ( n 3 ) o(n^3) o(n3)
中心扩展法,对每个位置中心扩展找回文串。回文中心的个数有 o ( n ) o(n) o(n)个,每个回文中心扩展的复杂度是 o ( n ) o(n) o(n),所以总体复杂度是 o ( n 2 ) o(n^2) o(n2)
中心扩展法,首先要判断怎么扩展。
对于长度为3的字符串,以abc
为例:可以扩展的回文中心下标有:(0, 0), (0, 1), (1, 1), (1, 2), (2, 2)
,即共有5
个
对于长度为4的字符串,同样可扩展的回文中心下标有:(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, 3)
,共有7
个
推断出,对于长度为n
的字符串,其可扩展的回文下标有2n - 1
个,写一下表格看看回文下标和扩展时左右的起始下标:
回文中心下标 | 左起始下标 | 右起始下标 |
---|---|---|
0 | 0 | 0 |
1 | 0 | 1 |
2 | 1 | 1 |
3 | 1 | 2 |
4 | 2 | 2 |
5 | 2 | 3 |
6 | 3 | 3 |
所以对于下标为i
的回文中心,左起始下标是i // 2
,右起始下标是i / 2
向上取余
Or just expand from the center, and the adjacent element.
代码
暴力版:
class Solution:
def countSubstrings(self, s: str) -> int:
def is_palindrome(s: str) -> bool:
return s == s[::-1]
cnt = 0
for i in range(len(s)):
for j in range(i, len(s)):
cnt += is_palindrome(s[i: j + 1])
return cnt
回文中心版:
class Solution:
def countSubstrings(self, s: str) -> int:
cnt = 0
for center in range(2 * len(s)):
left, right = center // 2, (center + 1) // 2
while 0 <= left and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
cnt += 1
return cnt
class Solution:
def countSubstrings(self, s: str) -> int:
res = 0
for i in range(len(s)):
# expand from the center
left, right = i, i
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
res += 1
# expand from the (adjacent, center)
left, right = i - 1, i
while left >= 0 and right < len(s) and s[left] == s[right]:
res += 1
left -= 1
right += 1
return res