-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEditDistance.cpp
More file actions
76 lines (59 loc) · 1.85 KB
/
EditDistance.cpp
File metadata and controls
76 lines (59 loc) · 1.85 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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//Levenshtein distance
//http://en.wikipedia.org/wiki/Levenshtein_distance
//Recursive will TLE
class Solution {
public:
int minDistance(string word1, string word2) {
return LevenshteinDistance(word1, word1.size(), word2, word2.size());
}
int LevenshteinDistance(string s, int len_s, string t, int len_t) {
if (len_s == 0) {
return len_t;
}
if (len_t == 0) {
return len_s;
}
int cost = 0;
if (s[len_s - 1] != t[len_t - 1]) {
cost = 1;
}
/* return minimum of delete char from s, delete char from t, and delete char from both */
return min(
min(LevenshteinDistance(s, len_s - 1, t, len_t), LevenshteinDistance(s, len_s, t, len_t - 1)) + 1,
LevenshteinDistance(s, len_s - 1, t, len_t - 1) + cost
);
}
};
class Solution {
public:
int minDistance(string word1, string word2) {
if (word1 == word2) {
return 0;
}
int lhs = (int)word1.size();
int rhs = (int)word2.size();
if (lhs == 0) {
return rhs;
}
if (rhs == 0) {
return lhs;
}
vector<vector<int> >distances(lhs + 1, vector<int>(rhs + 1, 0));
for (int i = 1; i <= lhs; ++i) {
distances[i][0] = i;
}
for (int i = 1; i <= rhs; ++i) {
distances[0][i] = i;
}
for (int i = 1; i <= lhs; ++i) {
for (int j = 1; j <= rhs; ++j) {
if (word1[i - 1] == word2[j - 1]) {
distances[i][j] = distances[i - 1][j - 1];
continue;
}
distances[i][j] = min(min(distances[i - 1][j] + 1, distances[i][j - 1] + 1), distances[i - 1][j - 1] + 1);
}
}
return distances[lhs][rhs];
}
};