Created
June 25, 2020 15:07
-
-
Save lychees/fcdd97dc1a98a04fbca6d7511c387803 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @param {string} word1 | |
* @param {string} word2 | |
* @return {number} | |
*/ | |
let minDistance = function(word1, word2) { | |
let a = word1.split("") | |
let b = word2.split("") | |
let n = a.length | |
let m = b.length | |
const INF = 3214567; | |
let dp = Array.from(Array(n+1), () => new Array(m+1)) | |
for (let i = 0; i <= n; i++) { | |
for (let j = 0; j <= m; j++) { | |
if (i + j === 0) { | |
dp[i][j] = 0; | |
continue; | |
} | |
dp[i][j] = INF | |
if (i > 0 && j > 0 && a[i - 1] == b[j - 1]) { | |
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1]) | |
} | |
if (i > 0 && j > 0 && a[i - 1] != b[j - 1]) { | |
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j - 1] + 1) | |
} | |
if (i > 0) { | |
dp[i][j] = Math.min(dp[i][j], dp[i - 1][j] + 1) | |
} | |
if (j > 0) { | |
dp[i][j] = Math.min(dp[i][j], dp[i][j - 1] + 1) | |
} | |
} | |
} | |
return dp[n][m] | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment