Skip to content

Commit f0fd75d

Browse files
authored
Create PalindromePartitioning
1 parent 23c8357 commit f0fd75d

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
#include<bits/stdc++.h>
2+
using namespace std;
3+
4+
#define int long long
5+
6+
void cpc()
7+
{
8+
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
9+
#ifndef ONLINE_JUDGE
10+
freopen("input.txt", "r", stdin);
11+
freopen("output.txt", "w", stdout);
12+
#endif
13+
}
14+
15+
int palpart(string s)
16+
{
17+
int n = s.length();
18+
19+
bool ispal[n][n];
20+
21+
for (int i = 0; i < n; i++)
22+
{ispal[i][i] = 1;}
23+
24+
for (int i = 0; i < n - 1; i++)
25+
{
26+
if (s[i] == s[i + 1])
27+
{ispal[i][i + 1] = 1;}
28+
else
29+
{ispal[i][i + 1] = 0;}
30+
}
31+
32+
for (int gap = 2; gap < n; gap++)
33+
{
34+
for (int i = 0; i < n - gap; i++)
35+
{
36+
if (s[i] == s[i + gap])
37+
{ispal[i][i + gap] = ispal[i + 1][i + gap - 1];}
38+
else
39+
{ispal[i][i + gap] = 0;}
40+
}
41+
}
42+
43+
int dp[n][n];
44+
45+
for (int i = 0; i < n; i++)
46+
dp[i][i] = 0;
47+
48+
for (int i = 0; i < n - 1; i++)
49+
{
50+
if (s[i] == s[i + 1])
51+
dp[i][i + 1] = 0;
52+
else
53+
dp[i][i + 1] = 1;
54+
}
55+
56+
for (int gap = 2; gap < n; gap++)
57+
{
58+
59+
for (int i = 0; i < n - gap; i++)
60+
{
61+
dp[i][i + gap] = gap;
62+
if (ispal[i][i + gap])
63+
{dp[i][i + gap] = 0;}
64+
else {
65+
for (int k = i; k < i + gap; k++)
66+
dp[i][i + gap] = min(dp[i][i + gap], 1 + dp[i][k] + dp[k + 1][i + gap]);
67+
}
68+
}
69+
}
70+
71+
return dp[0][n - 1];
72+
73+
}
74+
75+
76+
int32_t main()
77+
{
78+
cpc();
79+
80+
string s;
81+
cin >> s;
82+
83+
cout << palpart(s);
84+
return 0;
85+
}

0 commit comments

Comments
 (0)