Skip to content

Commit 47100b9

Browse files
agnivgcclaussCaedenPH
authored
Added code for palindrome partitioning problem under dynamic programming (#7222)
* Added code for palindrome partitioning problem under dynamic programming * Updated return type for function * Updated Line 24 according to suggestions * Apply suggestions from code review Co-authored-by: Caeden Perelli-Harris <[email protected]> * Update palindrome_partitioning.py * Update palindrome_partitioning.py * is_palindromic Co-authored-by: Christian Clauss <[email protected]> Co-authored-by: Caeden Perelli-Harris <[email protected]>
1 parent d1430aa commit 47100b9

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
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(string: str) -> int:
13+
"""
14+
Returns the minimum cuts needed for a palindrome partitioning of string
15+
16+
>>> find_minimum_partitions("aab")
17+
1
18+
>>> find_minimum_partitions("aaa")
19+
0
20+
>>> find_minimum_partitions("ababbbabbababa")
21+
3
22+
"""
23+
length = len(string)
24+
cut = [0] * length
25+
is_palindromic = [[False for i in range(length)] for j in range(length)]
26+
for i, c in enumerate(string):
27+
mincut = i
28+
for j in range(i + 1):
29+
if c == string[j] and (i - j < 2 or is_palindromic[j + 1][i - 1]):
30+
is_palindromic[j][i] = True
31+
mincut = min(mincut, 0 if j == 0 else (cut[j - 1] + 1))
32+
cut[i] = mincut
33+
return cut[length - 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 '{s}' is {ans}")

0 commit comments

Comments
 (0)