题目
leetcode
给你一个字符串 s ,请你统计并返回这个字符串中 回文子串 的数目。
回文字符串 是正着读和倒过来读一样的字符串。
子字符串 是字符串中的由连续字符组成的一个序列。
代码
package main
import "fmt"
func countSubstrings(s string) int {
if len(s) == 0 {
return 0
}
count := 0
for i := 0; i < len(s); i++ {
count += expend(s, i, i)
count += expend(s, i, i+1)
}
return count
}
func expend(s string, left int, right int) int {
count := 0
for left >= 0 && right < len(s) && s[left] == s[right] {
count++
left--
right++
}
return count
}
func main() {
s := "babad"
fmt.Println(countSubstrings(s))
}
解题思路
- 还是回文子串的问题, 那必须使用单字符和双字符各自扩展的方法来解
- 然后就没啥了, 用个全局变量来累计个数就行