leetcode-647. 回文子串

题目

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

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

示例 1:

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

示例 2:

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

注意:

输入的字符串长度不会超过1000。

解题思路

暴力,对每个位置都检查包含了该位置后,向后有几个字符能组成回文串。暴力遍历的时间复杂度是 o ( n 2 ) o(n^2) o(n2),检查回文串的时间复杂度是 o ( n ) o(n) o(n),总共复杂度是 o ( n 3 ) o(n^3) o(n3)

中心扩展法,对每个位置中心扩展找回文串。回文中心的个数有 o ( n ) o(n) o(n)个,每个回文中心扩展的复杂度是 o ( n ) o(n) o(n),所以总体复杂度是 o ( n 2 ) o(n^2) o(n2)

中心扩展法,首先要判断怎么扩展。
对于长度为3的字符串,以abc为例:可以扩展的回文中心下标有:(0, 0), (0, 1), (1, 1), (1, 2), (2, 2),即共有5
对于长度为4的字符串,同样可扩展的回文中心下标有:(0, 0), (0, 1), (1, 1), (1, 2), (2, 2), (2, 3), (3, 3),共有7

推断出,对于长度为n的字符串,其可扩展的回文下标有2n - 1个,写一下表格看看回文下标和扩展时左右的起始下标:

回文中心下标左起始下标右起始下标
000
101
211
312
422
523
633

所以对于下标为i的回文中心,左起始下标是i // 2,右起始下标是i / 2向上取余

Or just expand from the center, and the adjacent element.

代码

暴力版:

class Solution:
    def countSubstrings(self, s: str) -> int:
        def is_palindrome(s: str) -> bool:
            return s == s[::-1]
        cnt = 0
        for i in range(len(s)):
            for j in range(i, len(s)):
                cnt += is_palindrome(s[i: j + 1])
        return cnt

回文中心版:

class Solution:
    def countSubstrings(self, s: str) -> int:
        cnt = 0
        for center in range(2 * len(s)):
            left, right = center // 2, (center + 1) // 2
            while 0 <= left and right < len(s) and s[left] == s[right]:
                left -= 1
                right += 1
                cnt += 1
        return cnt
class Solution:
    def countSubstrings(self, s: str) -> int:
        res = 0
        for i in range(len(s)):
            # expand from the center
            left, right = i, i
            while left >= 0 and right < len(s) and s[left] == s[right]:
                left -= 1
                right += 1
                res += 1
            # expand from the (adjacent, center)
            left, right = i - 1, i
            while left >= 0 and right < len(s) and s[left] == s[right]:
                res += 1
                left -= 1
                right += 1
        return res
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值