-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathedit-distance_2(AC).cpp
55 lines (45 loc) · 997 Bytes
/
edit-distance_2(AC).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
// 1AC, space-optimized version using DP.
#include <algorithm>
#include <string>
using namespace std;
class Solution {
public:
int minDistance(string word1, string word2) {
int n1, n2;
if (n1 < n2) {
return minDistance(word2, word1);
}
n1 = (int)word1.length();
n2 = (int)word2.length();
if (n1 == 0) {
return n2;
} else if (n2 == 0) {
return n1;
}
int **dp;
dp = new int*[2];
dp[0] = new int[2 * (n2 + 1)];
dp[1] = dp[0] + (n2 + 1);
int i, j;
for (j = 0; j <= n2; ++j) {
dp[0][j] = j;
}
int flag = 1;
for (i = 1; i <= n1; ++i) {
dp[flag][0] = i;
for (j = 1; j <= n2; ++j) {
dp[flag][j] = min(dp[!flag][j] , dp[flag][j - 1]) + 1;
if (word1[i - 1] == word2[j - 1]) {
dp[flag][j] = min(dp[flag][j], dp[!flag][j - 1]);
} else {
dp[flag][j] = min(dp[flag][j], dp[!flag][j - 1] + 1);
}
}
flag = !flag;
}
int result = dp[!flag][n2];
delete[] dp[0];
delete[] dp;
return result;
}
};