647\. 回文子串

# 647. 回文子串 (opens new window)

# Description

Difficulty: 中等

Related Topics: 字符串 (opens new window), 动态规划 (opens new window)

给你一个字符串 s ,请你统计并返回这个字符串中 回文子串 的数目。

回文字符串 是正着读和倒过来读一样的字符串。

子字符串 是字符串中的由连续字符组成的一个序列。

具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。

示例 1:

输入:s = "abc"
输出:3
解释:三个回文子串: "a", "b", "c"
1
2
3

示例 2:

输入:s = "aaa"
输出:6
解释:6个回文子串: "a", "a", "a", "aa", "aa", "aaa"
1
2
3

提示:

  • 1 <= s.length <= 1000
  • s 由小写英文字母组成

# Solution

Language: JavaScript

/**
 * @param {string} s
 * @return {number}
 */
// 中心扩散法
var countSubstrings = function(s) {
  const n = s.length
  let sum = 0
  function check(l,r){
    let count = 0
      while(l>=0 && r<n && s[l]==s[r]){
          l--
          r++
          count++
      }
      return count   
  }
  for(let i = 0; i<n; i++){
      sum = sum + check(i,i)+check(i,i+1)
  }
  return sum
};

// 解题思路
// 1.首先定义一个变量count来计算回文子串的个数
// 2.然后使用双指针遍历出所有的子串(分别按顺序和逆序累加字符串),然后判断两个子串是否相等,若相等(即为回文子串)则count++
// 3.最后返回count即可

/**
 * @param {string} s
 * @return {number}
 */
var countSubstrings = function(s) {
    let count = 0;
    for (let i = 0; i < s.length; i++) {
        let s1 = '', s2 = '';
        for (let j = i; j < s.length; j++) {
            s1 = s1 + s[j], s2 = s[j] + s2;// 分别按顺序和逆序累加字符串
            if (s1 === s2) count++;
        }
    }
    return count;
};

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
上次更新: 2022/8/25 下午5:12:12