LeetCode:647. Palindromic Substrings

32 篇文章 0 订阅
30 篇文章 0 订阅

Given a string, your task is to count how many palindromic substrings in this string.

The substrings with different start indexes or end indexes are counted as different substrings even they consist of same characters.

Example 1:

Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".

Example 2:

Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

Note:

  1. The input string length won’t exceed 1000.

题意:求字符串中回环子串的个数
分析:假设A[left,right]是回环的,如果A[left-1]==A[right+1],必然A[left-1,right+1]也是回环的。
因此必须找到一个遍历的顺序。只要找到回环子串的对称轴,然后向外扩展,就可以遍历解空间,需要注意回环串长度是奇数的(从长度为1的子串遍历),以及回环串长度是偶数的(从长度是2的子串遍历)。
代码如下:

class Solution {
    public int countSubstrings(String s) {
        if(s==null||s.length()==0)
            return 0;
        LinkedList<Integer> left=new LinkedList<Integer>();
        LinkedList<Integer> right=new LinkedList<Integer>();
        left.addFirst(0);
        right.addFirst(0);
        for(int i=1;i<s.length();i++){
            left.addFirst(i);
            right.addFirst(i);
            if(s.charAt(i)==s.charAt(i-1))
            {
                left.addFirst(i-1);
                right.addFirst(i);
            }
        }
        int count=left.size();
        while(left.size()>0){
            int l=left.removeLast();
            int r=right.removeLast();
            while(l-1>=0&&r+1<s.length()&&s.charAt(l-1)==s.charAt(r+1)){
                count++;
                l--;
                r++;
            }
        }
        return count;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值