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
|
#include <iostream>
#include <string>
#include <algorithm>
//#include <gtest/gtest.h>
using std::string;
int editDistance(const string &A, const string &B) {
int m = B.length();
int n = A.length();
int D[n + 1][m + 1];
for (int i = 0; i < n + 1; i++) {
D[i][0] = i;
}
for (int j = 0; j < m + 1; j++) {
D[0][j] = j;
}
for (int j = 1; j < m + 1; j++) {
for (int i = 1; i < n + 1; i++) {
int insertion = D[i][j - 1] + 1;
int deletion = D[i - 1][j] + 1;
int match = D[i - 1][j - 1];
int mismatch = D[i - 1][j - 1] + 1;
if (A.at(i - 1) == B.at(j - 1)) {
D[i][j] = std::min(insertion, std::min(deletion, match));
} else {
D[i][j] = std::min(insertion, std::min(deletion, mismatch));
}
}
}
return D[n][m];
}
//TEST(EditDistance, d2) {
// ASSERT_EQ(0, editDistance("ab", "ab"));
//}
//TEST(EditDistance, d1) {
// ASSERT_EQ(1, editDistance("a", "x"));
//}
//
//TEST(EditDistance, d3) {
// ASSERT_EQ(3, editDistance("short", "ports"));
//}
//
//TEST(EditDistance, d4) {
// ASSERT_EQ(5, editDistance("editing", "distance"));
//}
int main() {
string str1;
string str2;
std::cin >> str1 >> str2;
std::cout << editDistance(str1, str2) << std::endl;
return 0;
}
|