鱼C论坛

 找回密码
 立即注册
查看: 2496|回复: 0

[学习笔记] Leetcode 132. Palindrome Partitioning II

[复制链接]
发表于 2020-9-24 02:13:11 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 Seawolf 于 2020-9-24 02:14 编辑

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.



Example 1:

Input: s = "aab"
Output: 1
Explanation: The palindrome partitioning ["aa","b"] could be produced using 1 cut.
Example 2:

Input: s = "a"
Output: 0
Example 3:

Input: s = "ab"
Output: 1


Constraints:

1 <= s.length <= 2000
s consists of lower-case English letters only.
class Solution:
    def minCut(self, s: str) -> int:
        if s == None or len(s) == 0:
            return 0
        
        # optimize 0-cut and 1-cut
        if s == s[::-1]: return 0
        for i in range(1, len(s)):
            if s[:i] == s[:i][::-1] and s[i:] == s[i:][::-1]:
                return 1
        
        # normal case
        dp = [math.inf for _ in range(len(s) + 1)]
        dp[0] = 0
        
        def cal_palindrome():
            palindrome = [[False for _ in s] for _ in s]
            N = len(s)
            
            # Odd
            for i in range(N):
                left = right = i
                while left >= 0 and right < N and s[left] == s[right]:
                    palindrome[left][right] = True
                    left -= 1
                    right += 1
            
            # Even
            for i in range(N):
                left, right = i, i + 1
                while left >= 0 and right < N and s[left] == s[right]:
                    palindrome[left][right] = True
                    left -= 1
                    right += 1
            return palindrome
        
        palindrome = cal_palindrome()            
        
        for i in range(1, len(s) + 1):
            for j in range(i):
                if palindrome[j][i - 1]:
                    dp[i] = min(dp[i], dp[j] + 1)
        
        # number of cut equals to number of palindrome - 1
        return dp[len(s)] - 1

本帖被以下淘专辑推荐:

想知道小甲鱼最近在做啥?请访问 -> ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2024-7-2 21:15

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表