-
Notifications
You must be signed in to change notification settings - Fork 0
/
edit-distance.js
46 lines (34 loc) · 981 Bytes
/
edit-distance.js
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
/**
* @param {string} word1
* @param {string} word2
* @return {number}
*/
var minDistance = function(word1, word2) {
var memo = new Array(word1.length+1);
for (var i = 0; i < memo.length; i++) {
memo[i] = new Array(word2.length+1);
memo[i].fill(-1);
}
var solve = (pos1, pos2) => {
if(pos1 >= word1.length) {
return word2.length - pos2;
}
if(pos2 >= word2.length) {
return word1.length - pos1;
}
if(memo[pos1][pos2] !== -1) {
return memo[pos1][pos2];
}
if(word1[pos1] !== word2[pos2]) {
memo[pos1][pos2] = Math.min(
solve(pos1 + 1, pos2 + 1) + 1,
solve(pos1 + 1, pos2) + 1,
solve(pos1, pos2 + 1) + 1
);
return memo[pos1][pos2];
}
memo[pos1][pos2] = solve(pos1 +1, pos2 +1);
return memo[pos1][pos2];
}
return solve(0, 0);
};