diff --git a/Palindrome-Partitioning/cs412_palindrome_dynamic.py b/Palindrome-Partitioning/cs412_palindrome_dynamic.py new file mode 100644 index 0000000..4b1860d --- /dev/null +++ b/Palindrome-Partitioning/cs412_palindrome_dynamic.py @@ -0,0 +1,52 @@ +""" +name: Nicholas Tamassia + +Honor Code and Acknowledgments: + + This work complies with the JMU Honor Code. + + Runtime: O(n^2). +""" + +# Analysis: +# The loop on line 23 iterates n times where n is the length of the input string. +# The loop on line 28 iterates n - i times, which despite being practically fewer +# steps on average than the line 23 loop, still scales linearly with the size of +# the input string. Because both loops are O(n) and the second is nested in the +# first, the overall runtime complexity is O(n^2). + + +def palindrome_partitions(s: str) -> int: + + n: int = len(s) + memo: list[int] = [0] * (n + 1) + memo[n] = 1 + + def is_palindrome(start: int, end: int) -> bool: + return s[start:end] == s[start:end][::-1] + + for i in range(n - 1, -1, -1): + + sum = 0 + + for j in range(i + 1, n + 1): + if is_palindrome(i, j): + sum += memo[j] + + memo[i] = sum + + return memo[0] + + +# All modules for CS 412 must include a main method that allows it +# to imported and invoked from other python scripts +def main(): + n: int = int(input()) + + for _ in range(0, n): + in_str = input().strip() + print(palindrome_partitions(in_str)) + + +if __name__ == "__main__": + main()