-
Notifications
You must be signed in to change notification settings - Fork 0
/
dailycoding031.cpp
75 lines (61 loc) · 1.74 KB
/
dailycoding031.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
75
#include <iostream>
#include <utility>
#include <map>
#include <string>
using std::string;
using std::cout;
using std::endl;
using std::map;
/*
* Helper to compute min of three numbers
*/
int min(int x, int y, int z) {
return std::min(std::min(x, y), z);
}
/*
* Find the minimum edit distance using dynamic programming
* storing edit distances for every substring in a table and
* building the table in a bottom up approach. Substitutions
* cost 1 unit if the characters at the corresponding indices
* are not equal.
*
* runs in O(m*n) time, O(m*n) space; m, n are the lengths of the strings
*/
int editDistance(string s1, string s2) {
int m = s1.length(), n = s2.length();
int tab[m + 1][n + 1];
// build the distance table bottom up
for (int i = 0; i <= m; i++) {
for (int j = 0; j <= n; j++) {
if (i == 0)
tab[i][j] = j;
else if (j == 0)
tab[i][j] = i;
else
tab[i][j] = min(tab[i - 1][j] + 1,
tab[i][j - 1] + 1,
tab[i - 1][j - 1] + (s1[i-1] != s2[j-1]));
}
}
return tab[m][n];
}
bool run_tests(map<int, std::pair<string, string>> tests) {
bool result = true;
for (std::pair<int, std::pair<string, string>> test: tests) {
result &= (test.first == editDistance(test.second.first, test.second.second));
}
return result;
}
int main() {
map<int, std::pair<string, string>> tests;
tests[3] = std::make_pair("kitten", "sitting");
tests[8] = std::make_pair("abcdefgh", "efghabcd");
tests[1] = std::make_pair("price", "rice");
tests[6] = std::make_pair("interleave", "ilnetaevre");
tests[4] = std::make_pair("a", "abcde");
if (run_tests(tests))
cout << "Passed" << endl;
else
cout << "Failed" << endl;
return 0;
}