[和小菜鸡一起刷题(python)] LeetCode 131. 分割回文串 (Palindrome Partitioning)

LeetCode 131. 分割回文串 (Palindrome Partitioning)

原题

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

返回 s 所有可能的分割方案。

示例:

输入: “aab”
输出:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]

思路

题目要求返回所有的可能方案,所以依旧采用回溯算法。循环查看当前字符串的每一个可切分位置位;判断若在当前位置切分,前半部分是否是回文串。若是,则将前半部分存入当前解,并递归分割后半部分。
例如输入字符串为示例:
|a  |a  |b  |
0 1 2 3 
首先判断分割位1,发现前半部分‘a’是回文串,将‘a’存入cur_res,将后半部分‘ab’用作递归。当输入字符串为空时,递归结束,将cur_res加入的result,最终返回result。

代码

class Solution(object):
    def partition(self, s):
        """
        :type s: str
        :rtype: List[List[str]]
        """
        if len(s) == 0:
            return []
        else:
            res = []
            self.partition_helper(s, [], res)
        return res

    def partition_helper(self, s, cur_res, result):
        if len(s) == 0:
            result.append(cur_res)
        for i in range(1, len(s)+1):
            if self.check(s[:i]):
                self.partition_helper(s[i:], cur_res + [s[:i]], result)


    def check(self, s):
        if len(s) == 0:
            return False
        else:
            start = 0
            end = len(s) - 1
            while start <= end:
                if s[start] != s[end]:
                    return False
                else:
                    start += 1
                    end -= 1
            return True
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值