-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathEdit_Distance.cpp
145 lines (110 loc) · 2.79 KB
/
Edit_Distance.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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
/*
*!Brute force Time complexity:O(3^n)
*! DP SOLUTION: TIme:O(m*n) space:O(m*n)
*!SPace optimized: Time:O(m*n) space:(m)
*/
//Brute force
#include<bits/stdc++.h>
using namespace std;
int editDistance(string s1, string s2)
{
if(s1.empty())
return s2.size();
if(s2.empty())
return s1.size();
if(s1==s2)
return 0;
int answer=0;
if(s1[0]!=s2[0])
{
int a=editDistance(s1.substr(1),s2);
int b=editDistance(s1,s2.substr(1));
int c=editDistance(s1.substr(1),s2.substr(1));
answer=min(a,min(b,c))+1;
}
else
{
answer= editDistance(s1.substr(1),s2.substr(1));
}
return answer;
}
//Better brute force, is to avoid using substr method
int min(int x, int y, int z) { return min(min(x, y), z); }
int editDist(string str1, string str2, int m, int n)
{
if (m == 0)
return n;
if (n == 0)
return m;
if (str1[m - 1] == str2[n - 1])
return editDist(str1, str2, m - 1, n - 1);
return 1
+ min(editDist(str1, str2, m, n - 1), // Insert
editDist(str1, str2, m - 1, n), // Remove
editDist(str1, str2, m - 1,
n - 1) // Replace
);
}
//*Memoization
int helper(string s1,string s2,int **arr)
{
int m=s1.size();
int n=s2.size();
if(s1.empty())
return s2.size();
if(s2.empty())
return s1.size();
if(s1==s2)
return 0;
if(arr[m][n]!=-1)
return arr[m][n];
if(s1[0]!=s2[0])
{
int a,b,c;
a=helper(s1.substr(1),s2,arr);
b=helper(s1,s2.substr(1),arr);
c=helper(s1.substr(1),s2.substr(1),arr);
arr[m][n]= min(a,min(b,c))+1;
}
else
arr[m][n]=helper(s1.substr(1),s2.substr(1),arr);
return arr[m][n];
}
int editDistance(string s1, string s2)
{
int m=s1.size();
int n=s2.size();
int i,j;
int **arr=new int*[m+1];
for(i=0;i<=m;i++)
arr[i]=new int[n+1];
for(i=0;i<=m;i++)
for(j=0;j<=n;j++)
arr[i][j]=-1;
return helper(s1,s2,arr);
}
// * Solution through DP
int editDistance(string s, string t) {
int m,n,i,j;
m=s.size();
n=t.size();
vector<vector<int>> dp(m+1,vector<int>(n+1));
dp[0][0]=0;
for(i=1;i<=n;i++)
dp[0][i]=i;
for(i=1;i<=m;i++)
dp[i][0]=i;
for(i=1;i<=m;i++){
for(j=1;j<=n;j++){
if(s[i-1]==t[j-1])
dp[i][j]=dp[i-1][j-1];
else{
int a = dp[i-1][j];
int b = dp[i][j-1];
int c = dp[i-1][j-1];
dp[i][j]=min(a,min(b,c))+1;
}
}
}
return dp[m][n];
}