LeetCode:647. Palindromic Substrings

LeetCode:647. Palindromic Substrings

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.

Example 1:

Input: "abc"
Output: 3
Explanation: Three palindromic strings: "a", "b", "c".
 

Example 2:

Input: "aaa"
Output: 6
Explanation: Six palindromic strings: "a", "a", "a", "aa", "aa", "aaa".

求一个字符串的所有回文子串。

思路一:中心扩展法

设N是原始字符串的长度,那么这个字符串的所有回文子串的中心可能有2N-1个情况:包括一个字符为中心(回文字串长度为奇数)和两个字符为中心(回文字串长度为偶数)。例如:字符串abc,它的可能的中心是[a,b,ab,c,bc],一共5种情况。

对于每个可能的中心x,我们x为中心向左右展开,计算所有以x为中心的回文子串。此外,如果一个字串 [a, b]是一个回文区间 (也就是 S[a], S[a+1], …, S[b] 是回文字符串), 那么 [a+1, b-1] 也是一个回文区间。

Python 代码实现

class Solution(object):
    def countSubstrings(self, S):
        N = len(S)
        ans = 0
        for center in range(2*N - 1):
            left = center // 2
            right = left + center % 2
            print(" l & r : ",left,right,center)
            while left >= 0 and right < N and S[left] == S[right]:
                ans += 1
                left -= 1
                right += 1
        return ans
思路二:动态规划

Python 代码实现

class Solution:
    def countSubstrings(self, s: str) -> int:
        n = len(s)
        res = 0
        dp = [[False for i in range(n)] for j in range(n)]

        for i in range(n)[::-1]:
            for j in range(i,n):
                dp[i][j] = s[i] == s[j] and (j - i <= 2 or dp[i + 1][j - 1])
                if(dp[i][j]):
                    res+=1
        
        return res

首先要明确:dp[i][j] 表示从 i 到 j 的子串是否是回文字符串s[i]表示 i 位置的字符。考虑如下两种情况:

  • 当j-i<=2且s[i]==s[j]时,i到j的子串为回文。这里很显然长度小于等于两个字符的时候,只要s[i]==s[j],那这个字符串肯定是回文;
  • 当j-i>2时,如果s[i]==s[j] 且 dp[i+1][j-1] ==True,那么i到j的子串为回文。因为dp[i+1][j-1]=True表示i+1到j-1位置的子串是回文,那么当s[i]==s[j]时,i到j的整个子串肯定也是回文。

总结一下,dp[i][i]为True的情况,可以用如下公式表示:
d p [ i ] [ j ] = T r u e { s [ i ] = s [ j ] j − i &lt; = 2 s [ i ] = = s [ j ] &MediumSpace; a n d &MediumSpace; d p [ i + 1 ] [ j − 1 ] j − i &gt; 2 dp[i][j]=True \begin{cases} s[i]=s[j] &amp; j-i&lt;=2 \\ s[i]==s[j] \:and\: dp[i+1][j-1] &amp; j-i&gt;2 \end{cases} dp[i][j]=True{s[i]=s[j]s[i]==s[j]anddp[i+1][j1]ji<=2ji>2

思路三:Manacher’s Algorithm 马拉车算法

此外还有一个时间复杂度为O(n)的算法,详细讲解看下面的两篇参考文章。

class Solution:
    def countSubstrings(self, S):
        def manachers(S):
            A = '@#' + '#'.join(S) + '#$'
            Z = [0] * len(A)
            center = right = 0
            for i in range(1, len(A) - 1):
                if i < right:
                    Z[i] = min(right - i, Z[2 * center - i])
                while A[i + Z[i] + 1] == A[i - Z[i] - 1]:
                    Z[i] += 1
                if i + Z[i] > right:
                    center, right = i, i + Z[i]
            return Z

        return sum((v+1)//2 for v in manachers(S))

参考:


THE END.

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值