Skip to content

Commit 3545a87

Browse files
authored
Create Minimum number of insertions to form a palindrome - DP.cpp
1 parent ad0ed1f commit 3545a87

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
// Dynamic programming solution
2+
#include <bits/stdc++.h>
3+
#include <ext/rope>
4+
using namespace std;
5+
using namespace __gnu_cxx;
6+
7+
using ld = long double;
8+
using llint = long long;
9+
using ullint = unsigned long long;
10+
using pii = pair <int,int>;
11+
using pcc = pair <char,char>;
12+
using pss = pair <string,string>;
13+
using vi = vector <int>;
14+
using vb = vector <bool>;
15+
using vii = vi::iterator;
16+
17+
#define INF (1<<30)
18+
#define MOD 1000000007
19+
#define mp make_pair
20+
#define mt make_tuple
21+
#define all(c) c.begin(), c.end()
22+
#define ms(name,val) memset(name, val, sizeof name)
23+
#define np nullptr
24+
25+
26+
int main()
27+
{
28+
ios_base::sync_with_stdio(0);
29+
//cin.tie(0);
30+
31+
string s;
32+
cin >> s;
33+
int n = s.size();
34+
vector <vi> DP(n, vi(n, 0));
35+
36+
for (int len = 1; len < n; ++len)
37+
{
38+
for (int i = 0; i+len < n; ++i)
39+
{
40+
int j = i+len;
41+
42+
if (s[i] == s[j])
43+
DP[i][j] = DP[i+1][j-1];
44+
else
45+
DP[i][j] = 1 + min(DP[i][j-1], DP[i+1][j]);
46+
}
47+
}
48+
49+
cout << DP[0][n-1] << '\n';
50+
51+
52+
return 0;
53+
}

0 commit comments

Comments
 (0)