-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEdit_Distance.cpp
More file actions
54 lines (39 loc) · 1.69 KB
/
Edit_Distance.cpp
File metadata and controls
54 lines (39 loc) · 1.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/***
Case 1: Last characters are same , ignore the last character.
Recursively solve for m-1, n-
Case 2: Last characters are not same then try all the possible operations recursively.
Insert a character into s1 (same as last character in string s2 so that last character in both the strings are same): now s1 length will be m+1,
s2 length : n, ignore the last character and Recursively solve for m, n-1.
Remove the last character from string s1. now s1 length will be m-1, s2 length : n, Recursively solve for m-1, n
Replace last character into s1 (same as last character in string s2 so that last character in both the strings are same): s1 length will be m, s2 length : n, ignore the last character and Recursively solve for m-1, n-1.
***/
#include <bits/stdc++.h>
using namespace std;
int main()
{
string s1,s2;
cout << "Enter the first string : ";
cin >> s1;
cout << "Enter the second string : ";
cin >> s2;
int n = s1.length();
int m = s2.length();
int dp[n+1][m+1]; //n+1 because 0 is null so 1..n+1 actual string
//base case
//If any of the string if empty then number of operations
//needed would be equal to the length of other string
//(Either all characters will be removed or inserted)
for (int i=0; i<=n; i++)
dp[i][0] = i;
for (int i=0; i<=m; i++) // ""
dp[0][i] = i;
for (int i=1; i<=n; i++)
for (int j=1; j<=m; j++) {
if(s1[i-1] == s2[j-1])
dp[i][j] = dp[i-1][j-1];
else
dp[i][j] = 1 + min(min(dp[i-1][j],dp[i][j-1]),dp[i-1][j-1]); //1 is the unit cost for all 3 operations, if chars mismatch we add 1 to the total cost.
}
cout << "Edit distance = " << dp[n][m] << endl;
return 0;
}