647. 回文子串 (动态规划)

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

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

示例 1:

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

示例 2:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/palindromic-substrings
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

注释代码超时 参考链接:https://blog.csdn.net/OneDeveloper/article/details/79853156
不超时参考链接 :https://blog.csdn.net/OneDeveloper/article/details/79853156

python 代码如下:

class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        """
        #超时
        
        n = len(s)
        if n == 0:
            return 0
        dp = [[0] * n for _ in range(n)]
        for i in range(n):
            dp[i][i] = 1
        for i in range(n - 2, -1, -1):
            for j in range(i + 1, n, 1):
                if j - i == 1:
                    dp[i][j] = 2
                    if s[i] == s[j]:
                        dp[i][j] += 1
                else:
                    dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]
                    if s[i] == s[j] and self.isPalindromic(s[i + 1 : j]):
                        dp[i][j] += 1
        print(dp)
        return dp[0][n - 1]
    def isPalindromic(self, s):
        flag = True
        rSubStr = s[::-1]
        #for i in range(len(s)//2):
            #if s[i] != rSubStr[i]:
            #    flag = False
        if s == rSubStr:
            flag = True
        else:
            flag = False
        return flag
    """
        n = len(s)
        dp = [[False] * n for _ in range(n)]
        count = 0
        for i in range(n - 1, -1, -1):
            for j in range(i, n, 1):
                dp[i][j] = (s[i] == s[j]) and(j - i <= 2 or dp[i + 1][j - 1])
                if dp[i][j]:
                    count += 1
        #print(count)
        return count
        
x = Solution()
s = "aaa"
x.countSubstrings(s)

两种求解方法都基于由外向内,判断子串sunstring(i+1,j-1)(即去头去尾的子串)是否为回文,以及该子串两头是否回文。

go代码如下:

package main

func countSubstrings(s string) int {
	n := len(s)
	count := 0
	var dp [][]bool
	dp = make([][]bool, 0)
	for i := 0; i < n; i ++ {
		var tmp []bool
		tmp = make([]bool, n)
		dp = append(dp, tmp)
	}
	//fmt.Println(dp)
	for i := n - 1; i >= 0; i -- {
		for j := i; j < n; j ++ {
			dp[i][j] = (s[i] == s[j]) && (j - i <= 2 || dp[i + 1][j - 1])
			if dp[i][j] {
				count ++
			}
		}
	}
	//fmt.Println(count)
	return count
}

func main()  {
	s := "aaa"
	countSubstrings(s)
}

你可能感兴趣的:(leetcode)