领扣LintCode算法问题答案-837. 回文子串

领扣LintCode算法问题答案-837. 回文子串

837. 回文子串

给定一个字符串,你的任务是数出有多少个回文子串在这个字符串内。
一个子串不同于其他的子串,当且仅当开始和结束位置不同。

输入的字符串长度不会超过1,000

样例 1:

输入: “abc”
输出: 3
解释:
3个回文字符串: “a”, “b”, “c”.

样例 2:

输入: “aba”
输出: 4
解释:
4个回文字符串: “a”, “b”, “a”, “aba”.

题解

public class Solution {
    /**
     * @param str: s string
     * @return: return an integer, denote the number of the palindromic substrings
     */
    public int countPalindromicSubstrings(String str) {
        // write your code here
        int count = 0;
        for (int i = 0; i < str.length(); i++) {
            int maxIndex = i;
            while (maxIndex < str.length()) {
                boolean palindromic = true;
                for (int j = i; j <= maxIndex; j++) {
                    if (str.charAt(j) != str.charAt(maxIndex - j + i)) {
                        palindromic = false;
                        break;
                    }
                }
                if (palindromic) {
                    count++;
                }
                maxIndex++;
            }
        }
        return count;
    }
}

原题链接点这里

鸣谢

非常感谢你愿意花时间阅读本文章,本人水平有限,如果有什么说的不对的地方,请指正。
欢迎各位留言讨论,希望小伙伴们都能每天进步一点点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

二当家的白帽子

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值