var minDistance = function (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];
};
执行结果:通过
执行用时:92 ms, 在所有 JavaScript 提交中击败了83.92%的用户
内存消耗:45.5 MB, 在所有 JavaScript 提交中击败了20.03%的用户
通过测试用例:1146 / 1146
参考链接
72. 编辑距离 - 力扣(LeetCode) (leetcode-cn.com)
动态规划解决编辑距离:思路清晰,代码注释详细 - 编辑距离 - 力扣(LeetCode) (leetcode-cn.com)
|