0
点赞
收藏
分享

微信扫一扫

LeetCode 剑指 Offer II 020. 回文子字符串的个数

左小米z 2022-04-22 阅读 70

LeetCode 剑指 Offer II 020. 回文子字符串的个数

文章目录

题目描述

给定一个字符串 s ,请计算这个字符串中有多少个回文子字符串。

具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被视作不同的子串。
示例 1:
输入:s = "abc"
输出:3
解释:三个回文子串: "a", "b", "c"

LeetCode 剑指 Offer II 020. 回文子字符串的个数
提示:


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

一、解题关键词


二、解题报告

1.思路分析

2.时间复杂度

3.代码示例

class Solution {
    public int countSubstrings(String s) {
        if (s == null || s.length() == 0) {
            return 0;
        }
        int count = 0;
        //字符串的每个字符都作为回文中心进行判断,中心是一个字符或两个字符
        for (int i = 0; i < s.length(); ++i) {
            count += countPalindrome(s, i, i);
            count += countPalindrome(s, i, i+1);
        }
        return count;
    }

    //从字符串的第start位置向左,end位置向右,比较是否为回文并计数
    private int countPalindrome(String s, int start, int end) {
        int count = 0;
        while (start >= 0 && end < s.length() && s.charAt(start) == s.charAt(end)) {
            count++;
            start--;
            end++;
        }
        return count;
    }
}

2.知识点

使用每个元素当作回文中心 讨论奇数偶数的情况

总结

相同题目

xxx

举报

相关推荐

0 条评论