LeetCode 647. Palindromic Substrings解题报告(python)

647. Palindromic Substrings

  1. Palindromic Substrings python solution

题目描述

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.
在这里插入图片描述

解析

palindromic是回文的意思,本题让我们计算整个数列中有多少个回文数列。两个回文数列可能内容一致,但是只要数列中的元素在原数列中的索引不同也可。
回文数列要求正序和逆序内容必须一致,所以是中心对称结构。那么我们一共有多少个可能的中心呢?
因为一个元素也可以构成回文数列,那么每个元素自己都可以作为中心。而且,对于偶数个的回文序列,他们的中心位于两个元素之间。所以可能的重心一共有2n-1个。

class Solution(object):
    def countSubstrings(self, s):

        res = 0
        n  = len(s)
        for i in range(0, n):
            res += 1
            left = i -1
            right = i + 1
            while left >= 0 and right < n and s[left] == s[right]:
                left -= 1
                right += 1
                res += 1
            left=i
            right=i+1
            while left>=0 and right <n and s[left] == s[right]:
                left-=1
                right+=1
                res+=1
        return res

Reference

https://leetcode.com/problems/palindromic-substrings/discuss/105687/Python-Straightforward-with-Explanation-(Bonus-O(N)-solution)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值