Skip to content

Commit bc5452b

Browse files
Alok NegiAlok Negi
Alok Negi
authored and
Alok Negi
committed
Added Palindrome Partitioning Solution in Dynamic Programming
1 parent 9d42195 commit bc5452b

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
// Dynamic Programming Solution for Palindrome Partitioning Problem
2+
#include <iostream>
3+
#include <bits/stdc++.h>
4+
#include <string.h>
5+
using namespace std;
6+
7+
int min(int a, int b) { return (a < b) ? a : b; }
8+
9+
int minPalPartion(char* str)
10+
{
11+
12+
int n = strlen(str);
13+
int C[n];
14+
bool P[n][n];
15+
16+
int i, j, k, L; // different looping variables
17+
18+
for (i = 0; i < n; i++) {
19+
P[i][i] = true;
20+
}
21+
22+
for (L = 2; L <= n; L++) {
23+
for (i = 0; i < n - L + 1; i++) {
24+
j = i + L - 1; // Set ending index
25+
26+
if (L == 2)
27+
P[i][j] = (str[i] == str[j]);
28+
else
29+
P[i][j] = (str[i] == str[j]) && P[i + 1][j - 1];
30+
}
31+
}
32+
33+
for (i = 0; i < n; i++) {
34+
if (P[0][i] == true)
35+
C[i] = 0;
36+
else {
37+
C[i] = INT_MAX;
38+
for (j = 0; j < i; j++) {
39+
if (P[j + 1][i] == true && 1 + C[j] < C[i])
40+
C[i] = 1 + C[j];
41+
}
42+
}
43+
}
44+
45+
return C[n - 1];
46+
}
47+
48+
// Driver program to test above function
49+
int main()
50+
{
51+
char str[] = "ababbbabbababa";
52+
cout <<"Min cuts needed for Palindrome Partitioning is " << minPalPartion(str);
53+
return 0;
54+
}

0 commit comments

Comments
 (0)