-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathEditDistance.cpp
69 lines (51 loc) · 1.1 KB
/
EditDistance.cpp
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include<iostream>
#include<cstring>
using namespace std;
/* Bottom Up DP */
int editDistanceBottomUp(char *a,char *b){
int m = strlen(a);
int n = strlen(b);
int dp[m+1][n+1];
for(int i=0;i<=m;i++){
for(int j=0;j<=n;j++){
if(i==0){
dp[i][j] = j;
}
else if(j==0){
dp[i][j]=i;
}
else{
if(a[i-1] == b[j-1]){
dp[i][j] = dp[i-1][j-1];
}
else{
dp[i][j] = min( dp[i-1][j-1],min(dp[i][j-1],dp[i-1][j])) + 1;
}
}
}
}
return dp[m][n];
}
/* Recursive Implementation */
int editDistanceRecursive(char *a,char *b,int i,int j){
if(i==strlen(a)){
return strlen(b)-j;
}
if(j==strlen(b)){
return strlen(a)-i;
}
if(a[i]==b[j]){
return editDistanceRecursive(a,b,i+1,j+1);
}
else {
return min(editDistanceRecursive(a,b,i,j+1),min(editDistanceRecursive(a,b,i+1,j+1),editDistanceRecursive(a,b,i+1,j)))+1;
}
}
int main(){
char a[100];
char b[100];
cin>>a>>b;
cout<<editDistanceRecursive(a,b,0,0)<<endl;
cout<<editDistanceBottomUp(a,b)<<endl;
return 0;
}