Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit e9c3a31

Browse files
committed
Add solution #72
1 parent 171e824 commit e9c3a31

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

0072-edit-distance.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/**
2+
* 72. Edit Distance
3+
* https://leetcode.com/problems/edit-distance/
4+
* Difficulty: Medium
5+
*
6+
* Given two strings word1 and word2, return the minimum number of operations required to
7+
* convert word1 to word2.
8+
*
9+
* You have the following three operations permitted on a word:
10+
* - Insert a character
11+
* - Delete a character
12+
* - Replace a character
13+
*/
14+
15+
/**
16+
* @param {string} word1
17+
* @param {string} word2
18+
* @return {number}
19+
*/
20+
var minDistance = function(word1, word2) {
21+
const cache = new Array(word1.length + 1).fill(0).map(() => new Array(word2.length + 1));
22+
23+
for (let i = 0; i <= word1.length; i++) {
24+
for (let j = 0; j <= word2.length; j++) {
25+
if (i === 0) {
26+
cache[0][j] = j;
27+
} else if (j === 0) {
28+
cache[i][0] = i;
29+
} else if (word1[i - 1] == word2[j - 1]) {
30+
cache[i][j] = cache[i - 1][j - 1];
31+
} else {
32+
cache[i][j] = Math.min(cache[i][j - 1], cache[i - 1][j - 1], cache[i - 1][j]) + 1;
33+
}
34+
}
35+
}
36+
37+
return cache[word1.length][word2.length];
38+
};

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@
7575
69|[Sqrt(x)](./0069-sqrtx.js)|Medium|
7676
70|[Climbing Stairs](./0070-climbing-stairs.js)|Easy|
7777
71|[Simplify Path](./0071-simplify-path.js)|Medium|
78+
72|[Edit Distance](./0072-edit-distance.js)|Medium|
7879
73|[Set Matrix Zeroes](./0073-set-matrix-zeroes.js)|Medium|
7980
74|[Search a 2D Matrix](./0074-search-a-2d-matrix.js)|Medium|
8081
75|[Sort Colors](./0075-sort-colors.js)|Medium|

0 commit comments

Comments
 (0)