1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
|
// @Title: 回文子串 (Palindromic Substrings)
// @Author: 15816537946@163.com
// @Date: 2019-09-16 15:31:45
// @Runtime: 0 ms
// @Memory: 2 MB
/*
* @lc app=leetcode.cn id=647 lang=golang
*
* [647] 回文子串
*
* https://leetcode-cn.com/problems/palindromic-substrings/description/
*
* algorithms
* Medium (57.80%)
* Likes: 134
* Dislikes: 0
* Total Accepted: 8.6K
* Total Submissions: 14.9K
* Testcase Example: '"abc"'
*
* 给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。
*
* 具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。
*
* 示例 1:
*
*
* 输入: "abc"
* 输出: 3
* 解释: 三个回文子串: "a", "b", "c".
*
*
* 示例 2:
*
*
* 输入: "aaa"
* 输出: 6
* 说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".
*
*
* 注意:
*
*
* 输入的字符串长度不会超过1000。
*
*
*/
func countSubstrings(s string) int {
if s == "" {
return 0
}
var cnt int
for i := range s {
cnt += isDrome(s, i, i)
cnt += isDrome(s, i, i+1)
}
return cnt
}
func isDrome(s string, lo, hi int) int {
var cnt int
for lo>= 0 && hi < len(s) && s[lo] == s[hi] {
cnt++
lo--
hi++
}
return cnt
}
|