Palindrome Partitioning 解答

Question

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

Return all possible palindrome partitioning of s.

For example, given s = "aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]

Solution

基本思路还是递归。每次只探究第一刀切在哪儿。这里,为了避免重复计算,我们用DP来先处理子串是否对称的问题。思路参见 Palindrom Subarrays

如果想进一步节省时间,可以参见 Word Break II 的解法,将每个子问题的解存起来。

 1 class Solution(object):
 2     def construction(self, s):
 3         length = len(s)
 4         self.dp = [[False for i in range(length)] for j in range(length)]
 5         for i in range(length):
 6             self.dp[i][i] = True
 7         for i in range(length - 1):
 8             if s[i] == s[i + 1]:
 9                 self.dp[i][i + 1] = True
10         for sub_len in range(3, length + 1):
11             for start in range(0, length - sub_len + 1):
12                 end = start + sub_len - 1
13                 if s[start] == s[end] and self.dp[start + 1][end - 1]:
14                     self.dp[start][end] = True
15     
16     def partition(self, s):
17         """
18         :type s: str
19         :rtype: List[List[str]]
20         """
21         self.construction(s)
22         result = []
23         self.helper(s, 0, [], result)
24         return result
25     
26     def helper(self, s, start, cur_list, result):
27         length = len(s)
28         if start == length:
29             result.append(list(cur_list))
30             return
32         for end in range(start, length):
33             if self.dp[start][end]:
35                 cur_list.append(s[start : end + 1])
36                 self.helper(s, end + 1, cur_list, result)
37                 cur_list.pop()
40     

由于Python本身对字符串的强大处理,这道题的解答也可以为:

(比上一个解法花时间多)

 1 class Solution(object):
 2     def partition(self, s):
 3         """
 4         :type s: str
 5         :rtype: List[List[str]]
 6         """
 7         return [[s[:i]] + rest
 8             for i in xrange(1, len(s)+1)
 9             if s[:i] == s[i-1::-1]
10             for rest in self.partition(s[i:])] or [[]]

 

posted @ 2015-11-03 11:21  树獭君  阅读(129)  评论(0编辑  收藏  举报