Skip to content

Commit 8bd1a0a

Browse files
authored
Update 72-edit-distance.js
1 parent d0de465 commit 8bd1a0a

File tree

1 file changed

+29
-0
lines changed

1 file changed

+29
-0
lines changed

72-edit-distance.js

+29
Original file line numberDiff line numberDiff line change
@@ -23,3 +23,32 @@ const minDistance = function(word1, word2) {
2323
}
2424
return dp[m][n];
2525
};
26+
27+
// another
28+
29+
/**
30+
* @param {string} word1
31+
* @param {string} word2
32+
* @return {number}
33+
*/
34+
const minDistance = function(word1, word2) {
35+
const m = word1.length, n = word2.length
36+
const dp = Array(n + 1).fill(0)
37+
for(let i = 1; i <= n; i++) dp[i] = i
38+
let pre = 0
39+
for(let i = 1; i <= m; i++) {
40+
pre = dp[0]
41+
dp[0] = i
42+
for(let j = 1; j <= n; j++) {
43+
let tmp = dp[j]
44+
if(word1[i - 1] === word2[j - 1]) {
45+
dp[j] = pre
46+
} else {
47+
dp[j] = Math.min(pre, dp[j], dp[j - 1]) + 1
48+
}
49+
pre = tmp
50+
}
51+
}
52+
53+
return dp[n]
54+
};

0 commit comments

Comments
 (0)