[leetcode] 647. Palindromic Substrings

Description

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.

分析

题目的意思是:判断一个字符串里有多少不同的回文子串。

  • 把string的每一个位置当作回文子串的中心位置串,如果回文子串长度为奇数是,中间位置只有一个i;如果回文子串为偶数时,中间未知就为i,i+1;然后向两边拓展,这样遍历完以后就能得到所有的情况。

C++实现

class Solution {
public:
    int countSubstrings(string s) {
        if(s.empty()) return 0;
        int count=0;
        for(int i=0;i<s.length();i++){
            helper(s,i,i,count);
            helper(s,i,i+1,count);
        }
        return count;
    }
private:
    void helper(string s,int i,int j,int &count){
        while(i>=0&&j<s.length()&&(s[i]==s[j])){
            i--;
            j++;
            count++;
        }
    }
};

Python实现

长度为n的字符串会生成2n-1组回文中心[l,r],其中l=i//2, r=i//2+i%2。只要从 0 到2n-2遍历 i,就可以得到所有可能的回文中心,这样就把奇数长度和偶数长度两种情况统一起来了。

class Solution:
    def countSubstrings(self, s: str) -> int:
        n = len(s)
        res = 0
        for i in range(2*n-1):
            left = i//2 
            right = i//2+i%2
            while left>=0 and right<n and s[left]==s[right]:
                left-=1
                right+=1
                res+=1
        return res

参考文献

[LeetCode] Palindromic Substrings 回文子字符串

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

农民小飞侠

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

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

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

打赏作者

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

抵扣说明:

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

余额充值