leetcode力扣647. 回文子串

给定一个字符串,你的任务是计算这个字符串中有多少个回文子串。

具有不同开始位置或结束位置的子串,即使是由相同的字符组成,也会被计为是不同的子串。

示例 1:

输入: "abc"
输出: 3
解释: 三个回文子串: "a", "b", "c".
示例 2:

输入: "aaa"
输出: 6
说明: 6个回文子串: "a", "a", "a", "aa", "aa", "aaa".

 

class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        res = 0
        length = len(s)
        for i in range(2*length-1):
            l = i/2
            r = i%2+l
            while l >= 0 and r < length and s[l]==s[r]:
                l -= 1
                r += 1
                res += 1
        return res

 

你可能感兴趣的:(leetcode)