LeetCode647: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".

Note:

  1. The input string length won't exceed 1000.

LeetCode:链接

动态规划的思想是,我们先确定所有的回文,即 string[start:end]是回文. 当我们要确定string[i:j] 是不是回文的时候,要确定:

1)string[i]等于string[j]吗?
2)string[i+1:j-1]是回文吗?

单个字符是回文;两个连续字符如果相等是回文;如果有3个以上的字符,需要两头相等并且去掉首尾之后依然是回文。

class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        n = len(s)
        dp = [[0] * n for i in range(n)]
        count = 0
        for i in range(n):
            for j in range(i):
                # 左右两字符相等同时dp[j+1][i-1]是回文或者i - j < 2也就是这两个字符挨着
                dp[j][i] = (s[i] == s[j]) & ((i - j < 2) | dp[j+1][i-1])
                if dp[j][i]:
                    count += 1
            # 单个字符是回文
            dp[i][i] = 1
            count += 1
        return count

猜你喜欢

转载自blog.csdn.net/mengmengdajuanjuan/article/details/84965211