1. 程式人生 > 實用技巧 >分割回文串

分割回文串

題目:Given 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.
給定一個字串s,將s分割成一些子串,使每個子串都是迴文串。
返回符合要求的最少分割次數。
迴文串:正讀和反讀都一樣的字串

示例:
輸入:"aab"
輸出:1
解釋:進行一次分割就可將s分割成["aa", "b"]

class Solution(object):
    def minCut(self, s):
        """
        :param s: str
        :return: int
        """
        l = len(s)
        dpPart = [[False] * l for _ in range(l)]
        dp = [i for i in range(l)]

        # 判斷迴文串,填充dpPart
        # 列舉字串長度
        for length in range(l):
            # 列舉子串開始位置,length==0表示子串長度為1
            for i in range(l):
                j = i + length
                if j >= l:
                    break
                if length == 0:
                    dpPart[i][j] = True
                elif length == 1:
                    dpPart[i][j] = (s[i] == s[j])
                else:
                    dpPart[i][j] = dpPart[i + 1][j - 1] and (s[i] == s[j])
        # 填充dp
        for i in range(1, l):
            if dpPart[0][i]:
                dp[i] = 0
                continue

            for j in range(1, i + 1):
                # 列舉以s[i]結尾的迴文串
                if (dpPart[j][i]):
                    dp[i] = min(dp[i], dp[j - 1] + 1)

        return dp[l - 1]


if __name__ == '__main__':
    result = Solution()
    count = result.minCut("aab")
    print(count)
# 1