• 分割回文串


    题目: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
    
    Live what we love, do what we do, follow the heart, and do not hesitate.
  • 相关阅读:
    Chapter 2: 随机变量
    数据集
    Chapter 1: 随机事件及其概率
    概率论与数理统计每周教学内容及作业
    概率论与数理统计教学内容
    Entity Framework search sequnce
    Runtime Complexity of .NET Generic Collection
    update the UI property cross thread
    打通技术的任督二脉
    windbg symbol path
  • 原文地址:https://www.cnblogs.com/failan/p/14174917.html
Copyright © 2020-2023  润新知