From 49d68b055a3f1388aa10cf369090694f800b3891 Mon Sep 17 00:00:00 2001 From: Qi Jia <13632059+jackeyjia@users.noreply.github.com> Date: Fri, 16 Jul 2021 22:46:56 -0700 Subject: [PATCH] add js solution for minDistance --- problems/0072.编辑距离.md | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/problems/0072.编辑距离.md b/problems/0072.编辑距离.md index 26f080fe..9ddca7c0 100644 --- a/problems/0072.编辑距离.md +++ b/problems/0072.编辑距离.md @@ -307,6 +307,32 @@ func Min(args ...int) int { ``` +Javascript: +```javascript +const minDistance = (word1, word2) => { + let dp = Array.from(Array(word1.length + 1), () => Array(word2.length+1).fill(0)); + + for(let i = 1; i <= word1.length; i++) { + dp[i][0] = i; + } + + for(let j = 1; j <= word2.length; j++) { + dp[0][j] = j; + } + + for(let i = 1; i <= word1.length; i++) { + for(let j = 1; j <= word2.length; j++) { + if(word1[i-1] === word2[j-1]) { + dp[i][j] = dp[i-1][j-1]; + } else { + dp[i][j] = Math.min(dp[i-1][j] + 1, dp[i][j-1] + 1, dp[i-1][j-1] + 1); + } + } + } + + return dp[word1.length][word2.length]; +}; +``` ----------------------- * 作者微信:[程序员Carl](https://mp.weixin.qq.com/s/b66DFkOp8OOxdZC_xLZxfw)