LeetCode 131. Palindrome Partitioning

这道题可以用dp来解决。对任意一条字符串,遍历其可能被分割的每个位置,检查分割点后面是否是回文串,而创建列表存储分割点前面子串所有可能的分割。

代码中dp[i]存储的即为s[0:i] 所有的回文分割字符串。所以对于新的位置i,遍历0~i-1之间的每一个位置j,如果s[j:i] 为回文串,则把dp[j]存储的所有分割与s[j:i]连接并append到dp[i]中,这样就得到了s[0:i] 的所有分割。最后输出dp[-1]即可。

代码:

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        length=len(s)
        # each position stores all palindrome substrings from s[0:i]
        dp = [[] for i in range(length+1)]
        for i in range(1, length+1):
            for j in range(i):
                if self.ispalindrome(s[j:i]):
                    if len(dp[j])>0:
                            for pos in range(len(dp[j])):
                                dp[i].append(dp[j][pos] + [s[j:i]])
                    else:
                        dp[i].append([s[j:i]])
        return dp[-1]
    
    # whether a string is palindrome or not
    def ispalindrome(self, s):
        front, end = 0, len(s)-1
        while front<=end:
            if s[front]!=s[end]:
                return False
            front+=1
            end-=1
        return True

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值