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(o^2),所以考虑动态规划,采用中心扩张的方法,长度为n的字符串有2*n-1个回环中心,将回环中心依次编号,设立left和right两个指针,从回环中心开始,依次向外扩张,若s[left]==s[right]且left和right在0到n的范围内咋回环个数加一并继续向外扩张,直到不满足条件,难点在于初始指针的确定。

如果回环中心在第i个字符上,则,left=right=i,此时回环中心为2*i,若回环中心在字符i,j之间,left=i,right=i+1,回环中心为2*i+1,所以当回环中心在center(第center个回环中心)时left=center/2,而right=center/2+center%2

故代码如下

def countSubstrings(self, S):
    N = len(S)
    ans = 0
    for center in xrange(2*N - 1):
        left = center / 2
        right = left + center %2
        while left >= 0and right <N and S[left] == S[right]:
            ans += 1
            left -=1
            right +=1
    return ans


练习:413


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

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

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

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值