647. 回文子串

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

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

示例 1:

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

示例 2:

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

提示:

  • 输入的字符串长度不会超过 1000 。
class Solution {
    // dp
    public int countSubstrings(String s) {
        boolean[][] dp = new boolean[s.length()][s.length()];
        int count = 0;
        for(int j=0;j<s.length();j++){
            for(int i=0;i<=j;i++){
                if((i==j)||(j-i==1 && s.charAt(i)==s.charAt(j))||(j-i>1 && s.charAt(i)==s.charAt(j) && dp[i+1][j-1])){
                    dp[i][j]=true;
                    count++;
                }
            }
        }
        return count;
    }
}

添加‘#’辅助

class Solution {
    public int countSubstrings(String s) {
        if(s.equals(""))return 0;
        StringBuilder str = new StringBuilder();
        str.append(s.charAt(0));
        for(int i=1;i<s.length();i++){
            str.append('#');
            str.append(s.charAt(i));
        }
        int count =0;
        for(int i=0;i<str.length();i++){
            int l=i-1,r=i+1;
            if(str.charAt(i)!='#')count++;
            while(l>=0&&r<str.length() && str.charAt(l)==str.charAt(r)){
                if(str.charAt(l)!='#')count++;
                l--;
                r++;
            }
        }
        return count;
    }
}

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindromic-substrings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值