算法列表

647. 回文子串 中等

布莱克2026-05-19 23:20中心扩展

问题:

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

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

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

示例 1:

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

示例 2:

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

回答:

var countSubstrings = function(s) {
    let res = 0;
    let n = s.length;
    for (let i = 0; i < n; i++) {
        //奇数中心
        res = res + expandAroundCenter(s, i, i);
        //偶数中心
        res = res + expandAroundCenter(s, i, i + 1);
    }
    return res;
};
var expandAroundCenter = function(s, i, j) {
    let num = 0;
    while (i >= 0 && j < s.length && s[i] == s[j]) {
        num++;
        i--;
        j++;
    }
    return num;
}


assistant