leetcode-131-分割回文串

题目描述:

leetcode-131-分割回文串

 

第一次提交:

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        res = []
        temp = []
        def backtrack(s,temp):
            if not s:
                res.append(temp)
            for i in range(1,len(s)+1):
                if helper(s[:i]):
                    backtrack(s[i:],temp+[s[:i]])
        def helper(s):
            if len(s) == 1:
                return True
            i, j = 0, len(s) - 1
            while i < j:
                if s[i] != s[j]:
                    return False
                i += 1
                j -= 1
            return True
        backtrack(s,[])
        return res

 优化:

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        res = []
        temp = []
        def backtrack(s,temp):
            if not s:
                res.append(temp)
            for i in range(1,len(s)+1):
                if s[:i][::-1] == s[:i]:
                    backtrack(s[i:],temp+[s[:i]])
        backtrack(s,[])
        return res

 

上一篇:Java实现 LeetCode 131 分割回文串


下一篇:千锋学习之day01