Skip to content

Commit 0ee772d

Browse files
Create palindrome_partitioning.py
Program in python for Palindrome Partitioning
1 parent a71618f commit 0ee772d

1 file changed

Lines changed: 31 additions & 0 deletions

File tree

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
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)

0 commit comments

Comments
 (0)