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

 class Solution(object):
def partition(self, s):
"""
:type s: str
:rtype: List[List[str]]
"""
Solution.res = []
self.DFS(s, [])
return Solution.res def DFS(self, s, stringlist):
if len(s) == 0:
Solution.res.append(stringlist)
# 如果一开始的substring是palin,把他存到stringlist中
for i in range(1, len(s)+1):
if self.isPalin(s[:i]):
self.DFS(s[i:], stringlist + [s[:i]]) def isPalin(self, s):
for i in range(len(s)):
if s[i] != s[len(s)-1-i]:
return False
return True


上一篇:2017云计算开源峰会 你是想听Linux谈开源还是想听OpenStack谈开源?


下一篇:Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(十二)之Error Handling with Exceptions