Leetcode: Palindrome Partitioning II

Question

iven a string s, partition s such that every substring of the partition is a palindrome.

Return the minimum cuts needed for a palindrome partitioning of s.

For example, given s = “aab”,
Return 1 since the palindrome partitioning [“aa”,”b”] could be produced using 1 cut.

Show Tags
Show Similar Problems

Solution

Analysis

Get idea from here.
recording the minimum cut for str[0:i], thinking about how to get cut[i+1] using cut[0] to cut[i].

Code

class Solution(object):
    def minCut(self, s):
        """ :type s: str :rtype: int """

        T = self.table(s)
        cut = [float('inf')]*len(s)
        cut[0] = 0
        for ind in range(1,len(cut)):
            cut[ind] = ind
            for j in range(ind+1):
                if T[j][ind]:
                    if j==0:
                        cut[ind] = 0
                    else:
                        cut[ind] = min(cut[ind], cut[j-1]+1)


        return cut[-1]


    def table(self, s):
        res = [x[:] for x in [[False,]*len(s)]*len(s)]
        for ind in range(len(s)):
            res[ind][ind] = True

        for ind in range(len(s)):
            l,r = ind-1, ind
            while l>=0 and r<len(s) and s[l]==s[r]:
                res[l][r] = True
                l -= 1
                r += 1
            l,r = ind-1, ind+1
            while l>=0 and r<len(s)  and s[l]==s[r]:
                res[l][r] = True
                l -= 1
                r += 1

        return res

Error Path

    1.
 if j==0:
     cut[ind] = 0

don’t consider this case that j starts from 0, cut[ind] will be at least 1 since cut[0] is 0,

2.

cut[ind] = ind
            for j in range(ind+1):
                if T[j][ind]:
                    if j==0:
                        cut[ind] = 0
                    else:
                        cut[ind] = min(cut[ind], cut[j-1]+1)

The for loop should end at (ind+1). That is because we need to know whether T[ind+1][ind+1] is palindrome or not.

你可能感兴趣的:(Leetcode: Palindrome Partitioning II)