Skip to content

Commit cb6e852

Browse files
authored
Create 72-edit-distance.js
1 parent bb67ac3 commit cb6e852

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

72-edit-distance.js

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @param {string} word1
3+
* @param {string} word2
4+
* @return {number}
5+
*/
6+
const minDistance = function(word1, word2) {
7+
let m = word1.length, n = word2.length;
8+
const dp = Array.from({length: m + 1}, ()=> new Array(n+ 1).fill(0))
9+
for (let i = 1; i <= m; i++) {
10+
dp[i][0] = i;
11+
}
12+
for (let j = 1; j <= n; j++) {
13+
dp[0][j] = j;
14+
}
15+
for (let i = 1; i <= m; i++) {
16+
for (let j = 1; j <= n; j++) {
17+
if (word1[i - 1] === word2[j - 1]) {
18+
dp[i][j] = dp[i - 1][j - 1];
19+
} else {
20+
dp[i][j] = Math.min(dp[i - 1][j - 1], Math.min(dp[i][j - 1], dp[i - 1][j])) + 1;
21+
}
22+
}
23+
}
24+
return dp[m][n];
25+
};

0 commit comments

Comments
 (0)