-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path0072-edit-distance.js
38 lines (35 loc) · 1 KB
/
0072-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
/**
* 72. Edit Distance
* https://leetcode.com/problems/edit-distance/
* Difficulty: Medium
*
* Given two strings word1 and word2, return the minimum number of operations required to
* convert word1 to word2.
*
* You have the following three operations permitted on a word:
* - Insert a character
* - Delete a character
* - Replace a character
*/
/**
* @param {string} word1
* @param {string} word2
* @return {number}
*/
var minDistance = function(word1, word2) {
const cache = new Array(word1.length + 1).fill(0).map(() => new Array(word2.length + 1));
for (let i = 0; i <= word1.length; i++) {
for (let j = 0; j <= word2.length; j++) {
if (i === 0) {
cache[0][j] = j;
} else if (j === 0) {
cache[i][0] = i;
} else if (word1[i - 1] == word2[j - 1]) {
cache[i][j] = cache[i - 1][j - 1];
} else {
cache[i][j] = Math.min(cache[i][j - 1], cache[i - 1][j - 1], cache[i - 1][j]) + 1;
}
}
}
return cache[word1.length][word2.length];
};