LeetCode 647 Palindromic Substrings (Python)

Posted by 小明MaxMing on March 27, 2021

题目

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.

解题思路

枚举回文串的中点(同时枚举奇数偶数长度),向两边拓展

代码

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

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅