comments: true
edit_url: https://github.com/doocs/leetcode/edit/main/lcof2/%E5%89%91%E6%8C%87%20Offer%20II%20020.%20%E5%9B%9E%E6%96%87%E5%AD%90%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E4%B8%AA%E6%95%B0/README.md
剑指 Offer II 020. 回文子字符串的个数
题目描述
给定一个字符串 s
,请计算这个字符串中有多少个回文子字符串。
具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
示例 1:
输入:s = "abc" 输出:3 解释:三个回文子串: "a", "b", "c"
示例 2:
输入:s = "aaa" 输出:6 解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
提示:
1 <= s.length <= 1000
s
由小写英文字母组成
注意:本题与主站 647 题相同:https://leetcode.cn/problems/palindromic-substrings/
解法
方法一:从中心向两侧扩展回文串
我们可以枚举回文串的中间点,然后向左右两边扩展,统计回文串的数量。注意,回文串可能包含奇数个字符,也可能不包含。因此这两种情况都要考虑。
时间复杂度 O ( n 2 ) O(n^2) O(n2),其中 n n n 是字符串 s
的长度。
Python3
class Solution:def countSubstrings(self, s: str) -> int:def f(i, j):cnt = 0while i >= 0 and j < n:if s[i] != s[j]:breakcnt += 1i, j = i - 1, j + 1return cntn = len(s)return sum(f(i, i) + f(i, i + 1) for i in range(n)) #【奇、偶扩展方式】
Java
class Solution {private String s;public int countSubstrings(String s) {int ans = 0;this.s = s;for (int i = 0; i < s.length(); ++i) {ans += f(i, i);ans += f(i, i + 1);}return ans;}private int f(int i, int j) {int cnt = 0;for (; i >= 0 && j < s.length() && s.charAt(i) == s.charAt(j); --i, ++j) {++cnt;}return cnt;}
}
C++
class Solution {
public:int countSubstrings(string s) {int ans = 0;int n = s.size();auto f = [&](int i, int j) -> int {int cnt = 0;for (; i >= 0 && j < n && s[i] == s[j]; --i, ++j) {++cnt;}return cnt;};for (int i = 0; i < n; ++i) {ans += f(i, i) + f(i, i + 1);}return ans;}
};
Go
func countSubstrings(s string) (ans int) {n := len(s)f := func(i, j int) (cnt int) {for ; i >= 0 && j < n && s[i] == s[j]; i, j = i-1, j+1 {cnt++}return}for i := range s {ans += f(i, i)ans += f(i, i+1)}return
}
Swift
class Solution {private var s: String = ""func countSubstrings(_ s: String) -> Int {var ans = 0self.s = slet length = s.countfor i in 0..<length {ans += countPalindromes(i, i)ans += countPalindromes(i, i + 1)}return ans}private func countPalindromes(_ i: Int, _ j: Int) -> Int {var cnt = 0var i = ivar j = jlet chars = Array(s)while i >= 0 && j < chars.count && chars[i] == chars[j] {cnt += 1i -= 1j += 1}return cnt}
}
方法二:Manacher 算法
在 Manacher 算法的计算过程中,用 d [ i ] d[i] d[i] 表示以第 i i i 位为中心的最大回文长度,以第 i i i 位为中心的回文串数量为 ⌈ p [ i ] 2 ⌉ \left \lceil \frac{p[i]}{2} \right \rceil ⌈2p[i]⌉。
时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( n ) O(n) O(n)。其中 n n n 是字符串 s
的长度。
【F05 Manacher(马拉车)】 https://www.bilibili.com/video/BV173411V7Ai/?share_source=copy_web&vd_source=ed4a51d52f6e5c9a2cb7def6fa64ad6a
Python3
class Solution:def countSubstrings(self, s: str) -> int:res=0t="$#"+"#".join(s)+"#" #转奇字符串n=len(t)d=[0]*nd[1],l,r=1,-1,-1 #初始化盒子边界l,r,回文半径1for i in range(2,n):#2)对于盒子内的情况,利用已知回文半径d和盒子范围[:i-1],递推未知d[i]if i<=r:d[i]=min(d[l+r-i],r-i+1)#1)对于盒子外的情况,暴力枚举判断回文,增加回文半径及盒子范围while i-d[i]>=0 and i+d[i]<n and t[i-d[i]]==t[i+d[i]]:d[i]+=1if i+d[i]-1>r:l,r=i-d[i]+1,i+d[i]-1res+=d[i]//2return res
Java
class Solution {public int countSubstrings(String s) {StringBuilder sb = new StringBuilder("^#");for (char ch : s.toCharArray()) {sb.append(ch).append('#');}String t = sb.append('$').toString();int n = t.length();int[] p = new int[n];int pos = 0, maxRight = 0;int ans = 0;for (int i = 1; i < n - 1; i++) {p[i] = maxRight > i ? Math.min(maxRight - i, p[2 * pos - i]) : 1;while (t.charAt(i - p[i]) == t.charAt(i + p[i])) {p[i]++;}if (i + p[i] > maxRight) {maxRight = i + p[i];pos = i;}ans += p[i] / 2;}return ans;}
}