Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@lychees
Created June 25, 2020 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lychees/fcdd97dc1a98a04fbca6d7511c387803 to your computer and use it in GitHub Desktop.
Save lychees/fcdd97dc1a98a04fbca6d7511c387803 to your computer and use it in GitHub Desktop.
/**
* @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