Skip to content

Commit da0f341

Browse files
committed
MinimumNumberOfDeletionsAndInsertions using c++
1 parent 7646839 commit da0f341

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
2+
/*
3+
Given two strings str1 and str2. The task is to remove or insert the minimum number of characters from/in str1 so as to transform it into str2. It could be possible that the same character needs to be removed/deleted from one point of str1 and inserted to some another point.
4+
5+
Example 1:
6+
7+
Input: str1 = "heap", str2 = "pea"
8+
Output: 3
9+
Explanation: 2 deletions and 1 insertion
10+
p and h deleted from heap. Then, p is
11+
inserted at the beginning One thing to
12+
note, though p was required yet it was
13+
removed/deleted first from its position
14+
and then it is inserted to some other
15+
position. Thus, p contributes one to the
16+
deletion_count and one to the
17+
insertion_count.*/
18+
19+
#include <bits/stdc++.h>
20+
using namespace std;
21+
22+
23+
class Solution{
24+
25+
26+
public:
27+
int LCS(string X, string Y, int m, int n){
28+
int dp[m+1][n+1];
29+
memset(dp,-1,sizeof(dp));
30+
for(int i=0;i<m+1;i++)
31+
{
32+
for(int j=0;j<n+1;j++)
33+
{
34+
if(i==0 || j==0) dp[i][j]=0;
35+
else if(X[i-1] == Y[j-1]){
36+
dp[i][j] = 1+dp[i-1][j-1];
37+
}
38+
else{
39+
dp[i][j] = max(dp[i-1][j] , dp[i][j-1]);
40+
}
41+
}
42+
}
43+
return dp[m][n];
44+
}
45+
int minOperations(string str1, string str2)
46+
{
47+
// Your code goes
48+
int len1 = str1.length();
49+
int len2 = str2.length();
50+
int lengthLCS = LCS(str1 , str2, len1, len2);
51+
return len1+ len2 - (2*lengthLCS);
52+
53+
}
54+
};
55+
56+
int main()
57+
{
58+
59+
60+
int t;
61+
cin >> t;
62+
while (t--)
63+
{
64+
string s1, s2;
65+
cin >> s1 >> s2;
66+
67+
Solution ob;
68+
cout << ob.minOperations(s1, s2) << "\n";
69+
70+
}
71+
return 0;
72+
}
73+

0 commit comments

Comments
 (0)