From 47100b992aef2fd5a7ae001155e3d0411db99ec9 Mon Sep 17 00:00:00 2001 From: Agniv Ghosh <73717822+agnivg@users.noreply.github.com> Date: Sun, 30 Oct 2022 18:45:46 +0530 Subject: [PATCH] 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 * Update palindrome_partitioning.py * Update palindrome_partitioning.py * is_palindromic Co-authored-by: Christian Clauss Co-authored-by: Caeden Perelli-Harris --- .../palindrome_partitioning.py | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 dynamic_programming/palindrome_partitioning.py diff --git a/dynamic_programming/palindrome_partitioning.py b/dynamic_programming/palindrome_partitioning.py new file mode 100644 index 000000000..c1629440e --- /dev/null +++ b/dynamic_programming/palindrome_partitioning.py @@ -0,0 +1,39 @@ +""" +Given a string s, partition s such that every substring of the +partition is a palindrome. +Find the minimum cuts needed for a palindrome partitioning of s. + +Time Complexity: O(n^2) +Space Complexity: O(n^2) +For other explanations refer to: https://www.youtube.com/watch?v=_H8V5hJUGd0 +""" + + +def find_minimum_partitions(string: str) -> int: + """ + Returns the minimum cuts needed for a palindrome partitioning of string + + >>> find_minimum_partitions("aab") + 1 + >>> find_minimum_partitions("aaa") + 0 + >>> find_minimum_partitions("ababbbabbababa") + 3 + """ + length = len(string) + cut = [0] * length + is_palindromic = [[False for i in range(length)] for j in range(length)] + for i, c in enumerate(string): + mincut = i + for j in range(i + 1): + if c == string[j] and (i - j < 2 or is_palindromic[j + 1][i - 1]): + is_palindromic[j][i] = True + mincut = min(mincut, 0 if j == 0 else (cut[j - 1] + 1)) + cut[i] = mincut + return cut[length - 1] + + +if __name__ == "__main__": + s = input("Enter the string: ").strip() + ans = find_minimum_partitions(s) + print(f"Minimum number of partitions required for the '{s}' is {ans}")