647. 回文子串

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

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

示例 1:

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

示例 2:

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

提示:

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

解法1:暴力,循环遍历出所有子串,然后判断子串是否是回文串。找出所有字串的时间复杂度是O(n^2),然后在用O(n)的时间来检查当前子串是不是回文串,所以时间复杂度是O(n^3).

class Solution {
     int num ;
    public  int countSubstrings(String s) {
        if(s == null || s.length() <=0) return 0;
        char[] ch = s.toCharArray();

        num = 0;
        for(int i = 0;i<ch.length ;i++){
            for(int j =i ;j<ch.length;j++){
                if(isPalindrome(ch,i,j)) num++;
            }
        }
        return num;
     }


    private  boolean isPalindrome(char[] ch, int start, int end) {
        
        if(end < start)  return false;
        if(start == end) return true;
        while(start<end ) {
            if(ch[start] == ch[end])
            {start++;end--;}
            else return false;
        }
        return true;
    }


}

解法2:中心扩展法,枚举每一个可能的回文中心,然后用两个指针分别向左右两边拓展,当两个指针指向的元素相同的时候就拓展,否则停止拓展。枚举回文中心的是 的时间复杂度是O(n),对于每个回文中心拓展的次数也是O(n) 的,所以时间复杂度是 O(n^2)

class Solution {
     int num ;
    public  int countSubstrings(String s) {
        if(s == null || s.length() <=0) return 0;
        char[] ch = s.toCharArray();

        num = 0;
        for(int i = 0;i<ch.length ;i++){
            isPalindrome(ch,i,i);
            isPalindrome(ch,i,i+1);
        }
        return num;
     }

    private  void isPalindrome(char[] ch, int start, int end) {

       //向两边扩展
        while(start>=0 && end<ch.length && ch[start] == ch[end]) {
            num++;
            start--;
            end++;
        }
    }

}

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值