LeetCode 647. 回文子串

//中心拓展法
class Solution {
    public int countSubstrings(String s) {
        //定义一个变量 统计有多少个回文子串
        int res = 0;
        //定义回文子串的中心点,可能是一个,也可能是2个 比如aba、abba
        //这里为什么是 2 * s.length()-1呢 奇数中心点有 s.length()个,偶数中心点有s.length() - 1个,回文子串共 2 * s.length()-1个中心点的情况
        for(int center = 0;center < 2 * s.length() - 1;center++){
            //定义 左,右 俩个指针,沿着中心点往外扩展,右指针可能指向left的位置, 也可能指向left的下一位
            int left = center / 2;
            int right = center / 2 + center % 2;
            //扩展
            while(left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)){
                left--;
                right++;
                res++;
            }
        }
        return res;
    }
}

或者LeetCode中有俩位同学的题解写的比较好理解,供参考

 

原文地址:https://www.cnblogs.com/peanut-zh/p/13893963.html