leetcode131 Palindrome Partitioning

 1 """
 2 Given a string s, partition s such that every substring of the partition is a palindrome.
 3 Return all possible palindrome partitioning of s.
 4 Example:
 5 Input: "aab"
 6 Output:
 7 [
 8   ["aa","b"],
 9   ["a","a","b"]
10 ]
11 """
12 """
13 两个解法 ,一递归二迭代 都很难理解
14 """
15 class Solution1:
16     def partition(self, s):
17         if not s:
18             return [[]]
19         path = []
20         res = []
21         self.dfs(s, path, res)
22         return res
23 
24     def dfs(self, s, path, res):
25         if not s:
26             res.append(path)
27         for i in range(1, len(s) + 1):  # 不理解,很难写
28             pre = s[:i]
29             if pre == pre[::-1]:
30                 self.dfs(s[i:], path + [pre], res)
31 
32 
33 class Solution2:
34     def partition(self, s):
35         """
36         :type s: str
37         :rtype: List[List[str]]
38         """
39         if not s:
40             return []
41         res = [[]]
42         for i, x in enumerate(s):
43             tmp = []
44             for r in res:
45                 tmp.append(r + [x])
46                 if len(r) >= 1 and r[-1] == x:
47                     tmp.append(r[:-1] + [r[-1] + x])
48 
49                 if len(r) >= 2 and r[-2] == x:
50                     tmp.append(r[:-2] + [r[-2] + r[-1] + x])
51 
52             res = tmp
53         return res
54 if __name__ == '__main__':
55     s = "aab"
56     ans = Solution2()
57     print(ans.partition(s))

 

posted @ 2020-03-04 15:54  yawenw  阅读(131)  评论(0编辑  收藏  举报