File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Function to check if a string is palindrome
2+ def is_palindrome (s ):
3+ return s == s [::- 1 ]
4+
5+ # Backtracking function to find all palindrome partitions
6+ def partition_helper (s , path , result ):
7+ # Base case: if string is empty, add the current path to result
8+ if not s :
9+ result .append (path )
10+ return
11+
12+ # Explore all possible partitions
13+ for i in range (1 , len (s ) + 1 ):
14+ prefix = s [:i ]
15+
16+ # If prefix is palindrome, recurse for the remaining string
17+ if is_palindrome (prefix ):
18+ partition_helper (s [i :], path + [prefix ], result )
19+
20+ # Main function
21+ def palindrome_partitioning (s ):
22+ result = []
23+ partition_helper (s , [], result )
24+ return result
25+
26+ # Example usage
27+ string = "aab"
28+ print ("All possible palindrome partitions of:" , string )
29+ partitions = palindrome_partitioning (string )
30+ for p in partitions :
31+ print (p )
You can’t perform that action at this time.
0 commit comments