Welcome to CodeYourCraft! Today, we're going to dive into an exciting problem known as Palindrome Partitioning. This problem is a great way to understand the power of dynamic programming and its applications in real-world projects.
Let's first understand what a palindrome is: A palindrome is a word, phrase, number, or other sequence of characters that reads the same forward and backward. For example, "racecar", "madam", and "121" are palindromes.
The Palindrome Partitioning problem asks us to partition a given string into substrings such that each substring is a palindrome. Let's take the word "babad", for example:
Palindrome Partitioning I (also known as Partitioning into Substrings) asks for the number of ways to partition a given string into substrings such that each substring is a palindrome.
Let's take the word "abca":
The total number of ways to partition "abca" into palindromes is 7 (4 + 3).
def count_palindromes(s):
n = len(s)
table = [[0 for _ in range(n)] for _ in range(n)]
# Base case: single character palindrome
for i in range(n):
table[i][i] = 1
# For each length greater than 1, check all possible starting indices
for k in range(1, n):
for i in range(n - k):
j = i + k
if s[i] == s[j] and k > 1 or k == 1:
table[i][j] = table[i + 1][j - 1] + (1 if s[i] == s[j] else 0)
else:
table[i][j] = table[i][j - 1] + table[i + 1][j]
return table[0][n - 1]
# Test the function
print(count_palindromes("abca")) # Output: 7Palindrome Partitioning II asks us to find all possible partitions of a given string into substrings such that each substring is a palindrome.
Let's take the word "babad":
The total number of valid partitions for "babad" is 2.
def partition(s):
n = len(s)
dp = [[False] * n for _ in range(n)]
# Base case: single character palindrome
for i in range(n):
dp[i][i] = True
# For each length greater than 1, check all possible starting indices
for k in range(1, n):
for i in range(n - k):
j = i + k
if s[i] == s[j] and k > 1 or k == 1:
if dp[i + 1][j - 1]:
dp[i][j] = True
elif s[i] == s[j - 1]:
if dp[i + 1][j]:
dp[i][j] = True
# Find all partitions
partitions = []
def find_partitions(i, j):
if i == j:
partitions.append([s[i:j + 1]])
elif dp[i][j]:
partitions.append(find_partitions(i + 1, j - 1))
partitions.append(find_partitions(i, j - 1))
find_partitions(0, n - 1)
# Print the partitions
for partition in partitions:
print(partition)
# Test the function
partition("babad")What is the main difference between Palindrome Partitioning I and Palindrome Partitioning II?