132. Palindrome Partitioning II

132. Palindrome Partitioning II

Hard

191954Add to ListShare

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.

 

参考详见:https://github.com/soulmachine/leetcode

 

class Solution:
    def minCut(self, s: str) -> int:
        """
        assert Solution().minCut("aab") == 1
        assert Solution().minCut("a") == 0
        """
        n = len(s)
        # f[i] 表示i -> n-1 最小剪数
        f = [0] * (n + 1)
        # p[i][j] 是否是回文数
        p = [[False for col in range(n)] for row in range(n)]
        # 初始化f,极端条件如 “abc” 每位各不相同需要 len("abc")-1 次剪刀
        for i in range(0, n + 1):
            f[i] = n - 1 - i
        for i in range(n - 1, -1, -1):
            for j in range(i, n):
                if s[i] == s[j] and (j - i < 2 or p[i + 1][j - 1]):
                    p[i][j] = True
                    f[i] = min(f[i], f[j + 1] + 1)
        return f[0]

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值