Skip to content

Commit 8ae7c99

Browse files
committed
Added code for palindrome partitioning problem under dynamic programming
1 parent 6e69181 commit 8ae7c99

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
"""
2+
Given a string s, partition s such that every substring of the
3+
partition is a palindrome.
4+
Find the minimum cuts needed for a palindrome partitioning of s.
5+
6+
Time Complexity: O(n^2)
7+
Space Complexity: O(n^2)
8+
For other explanations refer to: https://www.youtube.com/watch?v=_H8V5hJUGd0
9+
"""
10+
11+
12+
def find_minimum_partitions(s):
13+
"""
14+
Returns the minimum cuts needed for a palindrome partitioning of s
15+
16+
>>> find_minimum_partitions("aab")
17+
1
18+
>>> find_minimum_partitions("aaa")
19+
0
20+
>>> find_minimum_partitions("ababbbabbababa")
21+
3
22+
"""
23+
n = len(s)
24+
cut = [0 for i in range(n)]
25+
ispalindrome = [[False for i in range(n)] for j in range(n)]
26+
for i in range(n):
27+
mincut = i
28+
for j in range(i + 1):
29+
if s[i] == s[j] and (i - j < 2 or ispalindrome[j + 1][i - 1]):
30+
ispalindrome[j][i] = True
31+
mincut = min(mincut, 0 if j == 0 else (cut[j - 1] + 1))
32+
cut[i] = mincut
33+
return cut[n - 1]
34+
35+
36+
if __name__ == "__main__":
37+
s = input("Enter the string: ").strip()
38+
ans = find_minimum_partitions(s)
39+
print(f"Minimum number of partitions required for the string is {ans}")

0 commit comments

Comments
 (0)