Leetcode 131. Palindrome Partitioning

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 131. 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.

For example, given s = "aab",
Return

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

Keys: 1. 一般列出所有组合,可能性,etc 的题目都可以用DFS.

2. L8. 对于Class Solution中的全局变量x,可以用Solution.x

 

 1 class Solution(object):
 2     def partition(self, s):
 3         """
 4         :type s: str
 5         :rtype: List[List[str]]
 6         """
 7         Solution.res = []    
 8         self.DFS(s, [])
 9         return Solution.res
10                 
11     def DFS(self, s, stringlist):
12         if len(s) == 0:
13             Solution.res.append(stringlist)
14         # 如果一开始的substring是palin,把他存到stringlist中    
15         for i in range(1, len(s)+1):
16             if self.isPalin(s[:i]):
17                 self.DFS(s[i:], stringlist + [s[:i]])
18         
19             
20     def isPalin(self, s):
21         for i in range(len(s)):
22             if s[i] != s[len(s)-1-i]:
23                 return False
24         return True
25         
26         

 

 

 












以上是关于Leetcode 131. Palindrome Partitioning的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 131. Palindrome Partitioning

LeetCode131:Palindrome Partitioning

[leetcode-131-Palindrome Partitioning]

[LeetCode]题解(python):131-Palindrome Partitioning

leetcode 131. Palindrome Partitioning

[LeetCode] 131. Palindrome Partitioning Java