From 05c70e52ed9a0cdd8351d503636abc643f46d661 Mon Sep 17 00:00:00 2001 From: namanhere23 Date: Thu, 30 Oct 2025 20:29:02 +0530 Subject: [PATCH] Add Palindrome Partitioning algorithm implementation --- Algorithms/Palindrome Partitioning.cpp | 45 ++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Algorithms/Palindrome Partitioning.cpp diff --git a/Algorithms/Palindrome Partitioning.cpp b/Algorithms/Palindrome Partitioning.cpp new file mode 100644 index 0000000..0c1f77e --- /dev/null +++ b/Algorithms/Palindrome Partitioning.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; + +bool isPalindrome(string &s, int i, int j) { + while (i < j) { + if (s[i] != s[j]) + return false; + i++; + j--; + } + return true; +} + +int minCuts(string &s, int i, int j, vector> &dp) { + if (i >= j || isPalindrome(s, i, j)) + return 0; + + if (dp[i][j] != -1) + return dp[i][j]; + + int ans = INT_MAX; + + for (int k = i; k < j; k++) { + if (isPalindrome(s, i, k)) { + int right = minCuts(s, k + 1, j, dp); + ans = min(ans, 1 + right); + } + } + + return dp[i][j] = ans; +} + +int main() { + string s; + cout << "Enter a string: "; + cin >> s; + + int n = s.size(); + vector> dp(n, vector(n, -1)); + + cout << "Minimum number of cuts needed for palindrome partitioning: " + << minCuts(s, 0, n - 1, dp) << endl; + + return 0; +}