【Leetcode刷题】回文子串

https://leetcode-cn.com/problems/palindromic-substrings/

class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        # 遍历s,将每个位置的字符当做回文中心扩散
        n = len(s)
        # 一个字符也算是回文,所以开局count就是s中字符的数量
        count = n
        for i in range(n):
            # 如果有两个相同的字符,那么将这两个相同字符作为回文中心扩散
            if i+1 < n and s[i+1] == s[i]:
                count += 1
                left, right = i-1, i+2
                while left >= 0 and right < n and s[left] == s[right]:
                    count += 1
                    left -= 1
                    right += 1
            # 以当前字符作为回文中心开始扩散
            left, right = i-1, i+1
            while left >= 0 and right < n and s[left] == s[right]:
                count += 1
                left -= 1
                right += 1
        return count

时间复杂度:O(n2)

​ 首先需要遍历回文中心,回文中心可能是单个字符也可能是两个字符,单个字符的回文中心有n个,两个字符的回文中心最多有n-1个,因此最差情况需要遍历2n-1个回文中心,即O(2n-1)=O(n)的时间复杂度。

​ 而每个回文中心最多可能向外扩展n次,因此最终的时间复杂度为O(n2)

空间复杂度:O(1)

​ 没有使用额外的空间

原文地址:https://www.cnblogs.com/luozx207/p/13530954.html