131. Palindrome Partitioning

2019-07-25  本文已影响0人  葡萄肉多

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"]
]

题意

找到一个字符串所有可以构成回文的字串.

思路

回溯法。首先按一个字符切割,如果是回文,则存入path,再对字串同样操作,最后将path存入结果res;再按两个、三个……字符进行判断。

代码

class Solution:
    def partition(self, s: str) -> List[List[str]]:
        self.Palindrome = lambda s: s == s[::-1]
        res = []
        self.helper(s, res, [])
        return res

    def helper(self, s, res, path):
        if not s:
            res.append(path)
            return
        for i in range(1, len(s) + 1):
            if self.Palindrome(s[:i]):
                self.helper(s[i:], res, path + [s[:i]])
上一篇下一篇

猜你喜欢

热点阅读