使用动态规划解答相关题目
编辑距离【leetcode-72】
题目描述
给定两个字符串,求解通过插入或者替换是两个字符串相同的最小步骤
运行效率
代码如下
function minDistance(word1: string, word2: string): number {
if (!word2 || !word1) return word2.length || word1.length;
const dp = initDp();
getMinDistance(word1.length, word2.length);
return dp[word1.length][word2.length];
function getMinDistance(i: number, j: number) {
const lMin = dp[i - 1][j] ?? getMinDistance(i - 1, j);
const tMin = dp[i][j - 1] ?? getMinDistance(i, j - 1);
const ltMin = dp[i - 1][j - 1] ?? getMinDistance(i - 1, j - 1);
if (word1.charAt(i - 1) === word2.charAt(j - 1)) {
dp[i][j] = Math.min(lMin + 1, tMin + 1, ltMin);
} else {
dp[i][j] = Math.min(lMin, tMin, ltMin) + 1;
}
return dp[i][j];
}
function initDp() {
return new Array(word1.length + 1).fill(0).map((item, index) => {
const temp = [];
if (index === 0) {
for (let i = 0; i <= word2.length; i++) temp[i] = i;
} else {
temp.push(index);
}
return temp;
});
}
}
const res = minDistance("horse", "ros");
debugger;