forked from y-ncao/Python-Study
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPalindrome_Partitioning.py
44 lines (39 loc) · 1.02 KB
/
Palindrome_Partitioning.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
"""
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"]
]
```
"""
class Solution:
# @param s, a string
# @return a list of lists of string
def partition(self, s):
ret = []
self.partition_helper(s, [], ret)
return ret
def partition_helper(self, s, res, ret):
N = len(s)
if N == 0 :
ret.append(res[:])
return
for i in range(1, N+1): # This N+1 is important
if self.is_palindrome(s[:i]):
res.append(s[:i])
self.partition_helper(s[i:], res, ret)
res.pop()
def is_palindrome(self, s):
l = 0
r = len(s) - 1
while l < r:
if s[l] != s[r]:
return False
l += 1
r -= 1
return True
# This function can use return s == s[::-1] to replace.