Skip to content

Create Palindrome_partitioning.py #12061

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions backtracking/Palindrome_partitioning.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
def is_palindrome(s: str) -> bool:

Check failure on line 1 in backtracking/Palindrome_partitioning.py

View workflow job for this annotation

GitHub Actions / ruff

Ruff (N999)

backtracking/Palindrome_partitioning.py:1:1: N999 Invalid module name: 'Palindrome_partitioning'
"""
Helper function to check if a given string is a palindrome.

Args:
s (str): The string to check.

Returns:
bool: True if s is a palindrome, False otherwise.
"""
return s == s[::-1]


def backtrack(start: int, path: list, result: list, s: str):
"""
Backtracking function to find all palindrome partitions of the string s.

Args:
start (int): Starting index of the substring to consider.
path (list): The current path (partition) being constructed.
result (list): The final list of all valid palindrome partitions.
s (str): The input string.
"""
# If we've reached the end of the string, add the current path to the result
if start == len(s):
result.append(path[:]) # Add a copy of the current path to the result
return

# Try every possible partition starting from 'start'
for end in range(start + 1, len(s) + 1):
# If the current substring is a palindrome, we can proceed
if is_palindrome(s[start:end]):
path.append(s[start:end]) # Choose the current palindrome substring
backtrack(end, path, result, s) # Explore further partitions
path.pop() # Backtrack and remove the last chosen partition


def partition(s: str) -> list:
"""
Main function to find all palindrome partitions of a string.

Args:
s (str): The input string.

Returns:
list: A list of lists containing all valid palindrome partitions.
"""
result = [] # List to store all partitions
backtrack(0, [], result, s) # Start the backtracking process
return result


# Example usage:
s = "aab"
print(partition(s)) # Output: [['a', 'a', 'b'], ['aa', 'b']]
Loading