-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path0072-edit-distance.cpp
More file actions
30 lines (29 loc) · 958 Bytes
/
0072-edit-distance.cpp
File metadata and controls
30 lines (29 loc) · 958 Bytes
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
class Solution {
public:
int minDistance(string word1, string word2) {
int n = word1.size();
int m = word2.size();
int f[n + 1][m + 1];
for (int i = 0; i <= n; ++i) {
for (int j = 0; j <= m; ++j) {
if (i == 0 && j == 0) {
f[i][j] = 0;
} else if (i == 0) {
f[i][j] = j;
} else if (j == 0) {
f[i][j] = i;
} else {
f[i][j] = min(f[i - 1][j], f[i][j - 1]) + 1;
char ch1 = word1[i - 1];
char ch2 = word2[j - 1];
if (ch1 == ch2) {
f[i][j] = min(f[i][j], f[i - 1][j - 1]);
} else {
f[i][j] = min(f[i][j], f[i - 1][j - 1] + 1);
}
}
}
}
return f[n][m];
}
};