LeetCode 647. 回文子串(Palindromic Substrings)

647. 回文子串
647. Palindromic Substrings

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

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

LeetCode647. Palindromic Substrings中等

示例 1:

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

示例 2:

输入: "aaa"
输出: 6
说明: 6 个回文子串: "a", "a", "a", "aa", "aa", "aaa"。

注意:

  • 输入的字符串长度不会超过 1000。

Java 实现

class Solution {
    public int countSubstrings(String s) {
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            count += extractPalindrome(s, i, i);
            count += extractPalindrome(s, i, i + 1);
        }
        return count;
    }

    public int extractPalindrome(String s, int left, int right) {
        int count = 0;
        while (left >= 0 && right < s.length() && s.charAt(left) == s.charAt(right)) {
            count++;
            left--;
            right++;
        }
        return count;
    }
}
1306719-20190526163254343-1495615525.png

相似题目

参考资料

转载于:https://www.cnblogs.com/hglibin/p/10926473.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值