1. 程式人生 > >LeetCode--647. Palindromic Substrings(迴文字串個數)Python

LeetCode--647. Palindromic Substrings(迴文字串個數)Python

題目:

給定一個字串,計算該字串中有多少迴文子字串。

解題思路:

動態規劃,類似之前的一個題目,直接給連結和程式碼

http://blog.csdn.net/xiaoxiaoley/article/details/77407263

程式碼(Python):

class Solution(object):
    def countSubstrings(self, s):
        """
        :type s: str
        :rtype: int
        """
        dist = [[0]*len(s) for i in range(len(s))]  
        def f(i,j):  
            if(j-i==0):  
                dist[i][j] = 1  
                return 1  
            if(((j-i)==1) & (s[i]==s[j])):  
                dist[i][j] = 1  
                return 1  
            if(((j-i)==1) & (s[i]!=s[j])):  
                dist[i][j] = 0  
                return 0  
            if((s[i]==s[j])&(dist[i+1][j-1]==1)):  
                dist[i][j] = 1  
                return 1  
            else:  
                dist[i][j] = 0  
                return 0  
        i = len(s)-1  
        j = 0;  
        while(j<=len(s)-1):  
            for k in range(len(s)-j):  
                f(k,k+j)  
            j=j+1  
        
        count = 0
        for i in range(len(dist)):
            for j in range(len(dist)):
                if dist[i][j]:
                    count = count+1
        
        return count