-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdelete-operation-for-two-strings.cpp
55 lines (37 loc) · 1.6 KB
/
delete-operation-for-two-strings.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
class Solution {
public:
int minDistance(string word1, string word2) {
// longest common subsequence
// int word1Len = word1.size();
// int word2Len = word2.size();
// vector<vector<int>> dp(word1Len + 1,
// vector<int>(word2Len + 1, 0)
// );
// for (int i = 1; i<= word1Len; i++) {
// for (int j = 1; j<= word2Len; j++) {
// if ( word1[i - 1] == word2[ j - 1] ) {
// dp[i][j] = dp[i-1][j-1] + 1;
// } else {
// dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
// }
// }
// }
// int lcs = dp[word1Len][word2Len];
// return word1Len + word2Len - 2 * lcs;
int word1Len = size(word1);
int word2Len = size(word2);
vector<int> current(word2Len + 1, 0);
vector<int> previous(word2Len + 1, 0);
for (int i = 1; i <= word1Len; i++) {
for (int j = 1; j <= word2Len; j++) {
current[j] = word1[i-1] == word2[j-1]
?
previous[j-1]+ 1
: max(current[j-1], previous[j]);
}
previous = current;
}
int lcs = current[word2Len];
return word1Len + word2Len - 2 * lcs;
}
};