leetcod:分割回文串(python)

1. 问题描述

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。
返回 s 所有可能的分割方案。(回文串是正读反读顺序一样的字符串)

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

2. 思路

先将原字符串分割成左右两个部分,然后不管左边的字符串,将右边的字符串进行递归操作。但是在对右边的字符串进行递归操作之前需要验证左边的左边的字符串是回文串,然后将左边的字符串和右边字符串的递归结果,进行组合,返回最后结果。

2.1 python代码

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        res = []
        if s == "":
            return [[]]
        if len(s) == 1:
            return [[s]]
        strLenth = len(s)
        for i in range(1,strLenth+1):
            leftres = s[:i]  # 以aab为例,左字符串分别为a,aa,aab
            right = s[i:]
            if self.isPalindrome(leftres):
                rightres = self.partition(right)
                for i in rightres:
                    res.append([leftres]+i)
        return res     
    def isPalindrome(self,s):   # 判断是不是回文数
        i = 0
        j = len(s)-1
        while i < j:
            if s[i] != s[j]:
                return False
            i += 1
            j -= 1
        return True   

猜你喜欢

转载自blog.csdn.net/ggdhs/article/details/91347578