-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEdit_Distance
More file actions
35 lines (29 loc) · 1.06 KB
/
Edit_Distance
File metadata and controls
35 lines (29 loc) · 1.06 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
class Solution {
public:
int minDistance(string word1, string word2) {
vector<vector<int>> mind;
mind.assign(word1.length()+1, vector<int>(word2.length()+1));
mind[0][0]=0;
for (int i=0;i<=word1.length();i++){
for (int j=0;j<=word2.length();j++){
if (i==0) {
mind[i][j] = j;
continue;
}
if (j==0) {
mind[i][j] = i;
continue;
}
mind[i][j] = mind[i-1][j] < mind[i][j-1] ? mind[i-1][j]+1 : mind[i][j-1]+1;
if (word1[i-1]==word2[j-1]) {
if (mind[i-1][j-1] < mind[i][j]) mind[i][j] = mind[i-1][j-1];
}else{
if (mind[i-1][j-1]+1 < mind[i][j]) mind[i][j] = mind[i-1][j-1]+1;
}
}
}
if (word1.length()==0) return word2.length();
if (word2.length()==0) return word1.length();
return mind[word1.length()][word2.length()];
}
};