力扣 <每日一题> 647. 回文子串 中等

题目

给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。

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

示例 1:

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

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

提示:输入的字符串长度不会超过 1000 。

题解

class Solution {
    int num = 0;
    public int countSubstrings(String s) {
        
        for(int i = 0; i < s.length(); i++){
            counts(s, i, i); //回文串长度为奇数
            counts(s, i, i + 1);  //回文串长度为偶数
        }
        return num;
    }

    private void counts(String s, int start, int end){
        //以start和end为中点,左右两边同时添加1个字符进行比较
        while(start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)){
            num++;  //是回文串
            start--;  //往左移1位再判断
            end++; //往右移1位在判断
        }
    }
}

 

你可能感兴趣的:(每日一题)