Skip to content

Commit 3b3615c

Browse files
authored
added edit distance problem (#247)
Co-authored-by: Umang-IIT <73515380+Umang-IIT@users.noreply.github.com>
1 parent 3a40ff8 commit 3b3615c

File tree

2 files changed

+84
-0
lines changed

2 files changed

+84
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int minDistance(string A, string B) {
5+
int n = A.size(),m=B.size();
6+
7+
int dp[n][m];
8+
9+
for(int i=0;i<n;i++){
10+
bool exist = false;
11+
for(int j=0;j<=i;j++) if(A[j]==B[0]) exist = true;
12+
13+
if(exist) dp[i][0] = i;
14+
else dp[i][0] = i+1;
15+
}
16+
17+
for(int i=0;i<m;i++){
18+
bool exist = false;
19+
for(int j=0;j<=i;j++) if(A[0]==B[j]) exist = true;
20+
21+
if(exist) dp[0][i] = i;
22+
else dp[0][i] = i+1;
23+
}
24+
25+
for(int i=1;i<n;i++){
26+
for(int j=1;j<m;j++){
27+
if(A[i]==B[j]) dp[i][j] = dp[i-1][j-1];
28+
else{
29+
dp[i][j] = 1+min(dp[i][j-1],min(dp[i-1][j],dp[i-1][j-1]));
30+
}
31+
}
32+
}
33+
34+
return dp[n-1][m-1];
35+
36+
}
37+
38+
signed main()
39+
{
40+
string A,B;
41+
cin>>A>>B;
42+
cout<<minDistance(A,B);
43+
44+
return 0;
45+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# Edit Distance
2+
3+
The edit distance between two strings is the minimum number of operations required to transform one string into the other.
4+
5+
The allowed operations are:
6+
<ul>
7+
<li>Add one character to the string.</li>
8+
<li>Remove one character from the string.</li>
9+
<li>Replace one character in the string.</li>
10+
</ul>
11+
12+
For example, the edit distance between LOVE and MOVIE is 2, because you can first replace L with M, and then add I.
13+
14+
Your task is to calculate the edit distance between two strings.
15+
16+
### Input:
17+
```
18+
The first argument of input contains a string, A.
19+
The second argument of input contains a string, B.
20+
```
21+
### Output:
22+
```
23+
Return an integer, representing the minimum number of steps required.
24+
```
25+
26+
### Constraints:
27+
28+
- 1 <= length(A), length(B) <= 450
29+
30+
### Example:
31+
Input 1:<br>
32+
A = "abad"<br>
33+
B = "abac"
34+
35+
Output 1:<br>
36+
1
37+
38+
Explanation 1:<br>
39+
Operation 1: Replace d with c.

0 commit comments

Comments
 (0)