forked from kamyu104/LintCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
edit-distance.cpp
74 lines (62 loc) · 1.84 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
// Time: O(m * n)
// Space: O(min(m, n))
// DP with rolling window
class Solution {
public:
/**
* @param word1 & word2: Two string.
* @return: The minimum number of steps.
*/
int minDistance(string word1, string word2) {
const size_t m = word1.size();
const size_t n = word2.size();
if (m < n) {
return minDistance(word2, word1);
}
vector<vector<int>> steps(2, vector<int>(n + 1, 0));
for (int j = 0; j < n + 1; ++j) {
steps[0][j] = j;
}
for (int i = 1; i < m + 1; ++i) {
steps[i % 2][0] = i;
for (int j = 1; j < n + 1; ++j) {
steps[i % 2][j] = word1[i - 1] == word2[j - 1] ?
steps[(i - 1) % 2][j - 1] :
1 + min(steps[(i - 1) % 2][j - 1],
min(steps[(i - 1) % 2][j], steps[i % 2][j - 1]));
}
}
return steps[m % 2][n];
}
};
// Time: O(m * n)
// Space: O(m * n)
// DP
class Solution2 {
public:
/**
* @param word1 & word2: Two string.
* @return: The minimum number of steps.
*/
int minDistance(string word1, string word2) {
const size_t m = word1.size();
const size_t n = word2.size();
if (m < n) {
return minDistance(word2, word1);
}
vector<vector<int>> steps(m + 1, vector<int>(n + 1, 0));
for (int j = 0; j < n + 1; ++j) {
steps[0][j] = j;
}
for (int i = 1; i < m + 1; ++i) {
steps[i][0] = i;
for (int j = 1; j < n + 1; ++j) {
steps[i][j] = word1[i - 1] == word2[j - 1] ?
steps[i - 1][j - 1] :
1 + min(steps[i - 1][j - 1],
min(steps[i - 1][j], steps[i][j - 1]));
}
}
return steps[m][n];
}
};