Leetcode: Palindrome Partitioning II

本文介绍了一种算法,用于计算将给定字符串分割成全部由回文子串组成的最少分割数。通过动态规划的方法记录每个子串到当前字符的最少分割次数,并利用回文判断辅助表优化过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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. 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值