-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path131_medium_[backtrack]_palindrome_partitioning.py
66 lines (42 loc) · 1.76 KB
/
131_medium_[backtrack]_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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
from typing import List, DefaultDict, Set
from collections import defaultdict
class Solution:
def partition(self, s: str) -> List[List[str]]:
if len(s) == 0:
return []
if len(s) == 1:
return [[s]]
adjList = defaultdict(set)
palindrome_node_candidate_set = set()
for i in range(len(s)):
palindrome_node_candidate_set.add((i, i))
adjList[i].add((i+1, s[i]))
if i == len(s)-1:
break
if s[i] == s[i+1]:
palindrome_node_candidate_set.add((i, i+1))
adjList[i].add((i+2, s[i:i+2]))
while len(palindrome_node_candidate_set) > 0:
start_index, end_index = palindrome_node_candidate_set.pop()
next_start_index = start_index-1
next_end_index = end_index+1
if next_start_index < 0 or next_end_index > len(s)-1:
continue
if s[next_start_index] == s[next_end_index]:
palindrome_node_candidate_set.add((next_start_index, next_end_index))
adjList[next_start_index].add((next_end_index+1, s[next_start_index:next_end_index+1]))
def dfs(node_num: int, cache: List[str], adjList, answer: List[List[str]]) -> None:
if node_num == len(s):
answer.append(cache[:])
return
for (next_index, palindrome) in adjList[node_num]:
cache.append(palindrome)
dfs(next_index, cache, adjList, answer)
cache.pop()
answer = []
dfs(0, [], adjList, answer)
return answer
if __name__ == '__main__':
s = Solution()
print(s.partition('aab'))
print(s.partition('efe'))