美文网首页
leetcode131. Palindrome Partitio

leetcode131. Palindrome Partitio

作者: 就是果味熊 | 来源:发表于2020-06-24 18:20 被阅读0次

原题链接https://leetcode.com/problems/palindrome-partitioning/

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example:

Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        
        def isPalindrome(s):
            # n = len(s)
            # if len(s) <= 1:
            #     return True
            # for i in range((n + 1) // 2):
            #     if s[i] != s[n-1-i]:
            #         return False
            # return True
            return s == s[::-1]
        
        def backtrack(path,s):
            if not s:
                res.append(path[:])
                return
            for i in range(len(s)):
                if isPalindrome(s[:i+1]):
                    path.append(s[:i+1])
                    backtrack(path,s[i+1:])
                    path.pop()
        res = []
        path = []
        backtrack(path,s)
        return res

相关文章

网友评论

      本文标题:leetcode131. Palindrome Partitio

      本文链接:https://www.haomeiwen.com/subject/mihdfktx.html