leetcode专题训练647. Palindromic Substrings

该博客讨论了一种算法,用于计算给定字符串中所有回文子串的数量。算法首先考虑长度为1的子串,然后分别遍历长度为偶数和奇数的回文子串,从中心位置向外扩展并更新计数。这种方法有效地处理了不同长度的回文子串,并优化了搜索过程。
摘要由CSDN通过智能技术生成

这道题我的思路是找到所有可能的中心位置,再从中心位置扩展,找到所有的回文子串。比如一个长度为5的串,其中心位置可能为0、1、2、3、4索引位置,那么回文子串长度就为奇数,也可能是0、1之间,1、2之间,2、3之间,3、4之间,4、5之间,那么回文子串长度就为偶数。从中心位置开始往外扩展,直到扩展到边界或者不再是回文子串。具体看注释。

class Solution:
    def countSubstrings(self, s: str) -> int:
        l = len(s)
        if l == 0:
            return 0
        if l == 1:
            return 1
		
		# 先把结果加上长度为1的所有回文子串
        result = l
        
        # 长度为偶数的所有回文子串
        for i in range(l-1):
            left = i
            right = i+1
            now_result = 0
            # 判断是否扩展到边界
            while left >= 0 and right < l:
            	# 不再是回文子串
                if s[left] != s[right]:
                    break
                # 是回文子串,则加1
                now_result += 1
                # 从中心位置往外扩展
                left -= 1
                right += 1
            result += now_result
		
		# 由于长度为奇数且长度不为0的最短的回文子串长度为3,则l=2的情况特殊判断。
        if l == 2:
            return result

        # 长度为奇数且不为1的所有回文子串
        for i in range(l-2):
            left = i
            right = i+2
            now_result = 0
            while left >= 0 and right < l:
                if s[left] != s[right]:
                    break
                now_result += 1
                left -= 1
                right += 1
            result += now_result
            
        return result

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值