1
1
def is_palindrome (s : str ) -> bool :
2
2
"""
3
3
Helper function to check if a given string is a palindrome.
4
-
4
+
5
5
Args:
6
6
s (str): The string to check.
7
-
7
+
8
8
Returns:
9
9
bool: True if s is a palindrome, False otherwise.
10
10
"""
11
11
return s == s [::- 1 ]
12
12
13
+
13
14
def backtrack (start : int , path : list , result : list , s : str ):
14
15
"""
15
16
Backtracking function to find all palindrome partitions of the string s.
16
-
17
+
17
18
Args:
18
19
start (int): Starting index of the substring to consider.
19
20
path (list): The current path (partition) being constructed.
@@ -24,7 +25,7 @@ def backtrack(start: int, path: list, result: list, s: str):
24
25
if start == len (s ):
25
26
result .append (path [:]) # Add a copy of the current path to the result
26
27
return
27
-
28
+
28
29
# Try every possible partition starting from 'start'
29
30
for end in range (start + 1 , len (s ) + 1 ):
30
31
# If the current substring is a palindrome, we can proceed
@@ -33,20 +34,22 @@ def backtrack(start: int, path: list, result: list, s: str):
33
34
backtrack (end , path , result , s ) # Explore further partitions
34
35
path .pop () # Backtrack and remove the last chosen partition
35
36
37
+
36
38
def partition (s : str ) -> list :
37
39
"""
38
40
Main function to find all palindrome partitions of a string.
39
-
41
+
40
42
Args:
41
43
s (str): The input string.
42
-
44
+
43
45
Returns:
44
46
list: A list of lists containing all valid palindrome partitions.
45
47
"""
46
48
result = [] # List to store all partitions
47
49
backtrack (0 , [], result , s ) # Start the backtracking process
48
50
return result
49
51
52
+
50
53
# Example usage:
51
54
s = "aab"
52
55
print (partition (s )) # Output: [['a', 'a', 'b'], ['aa', 'b']]
0 commit comments