-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path72.cpp
More file actions
47 lines (43 loc) · 1.26 KB
/
72.cpp
File metadata and controls
47 lines (43 loc) · 1.26 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
#include <iostream>
using namespace std;
int sim(int (*dp)[501], string &word1, string &word2, int p1, int p2, int ops)
{
if (dp[p1][p2] != 0)
{
return dp[p1][p2] + ops;
}
else if (p1 >= word1.length() && p2 >= word2.length())
{
dp[p1][p2] = 0;
}
else if (p1 >= word1.length())
{
dp[p1][p2] = sim(dp, word1, word2, p1, p2 + 1, ops + 1) - ops; // add to word1
}
else if (p2 >= word2.length())
{
dp[p1][p2] = sim(dp, word1, word2, p1 + 1, p2, ops + 1) - ops; // remove from word1
}
else if (word1[p1] == word2[p2])
{
dp[p1][p2] = sim(dp, word1, word2, p1 + 1, p2 + 1, ops) - ops; // match!
}
else
{
int addW1 = sim(dp, word1, word2, p1, p2 + 1, ops + 1); // add to word1
int removeW1 = sim(dp, word1, word2, p1 + 1, p2, ops + 1); // remove from word1
int replaceW1 = sim(dp, word1, word2, p1 + 1, p2 + 1, ops + 1); // replace in word1
dp[p1][p2] = std::min(addW1, std::min(removeW1, replaceW1)) - ops;
}
return dp[p1][p2] + ops;
}
int minDistance(string word1, string word2)
{
int dp[501][501] = {{0}};
return sim(dp, word1, word2, 0, 0, 0);
}
int main()
{
cout << minDistance("horse", "ros") << endl;
return 0;
}