Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.)
You have the following 3 operations permitted on a word:
a) Insert a character
b) Delete a character
c) Replace a character
给定两个单词word1和word2,找到将word1转换为word2所需的最小步数。 (每个操作都算作1步。)
你有一个单词允许以下3个操作:
a)插入一个字符
b)删除一个字符
c)替换一个字符
/**
* @param {string} word1
* @param {string} word2
* @return {number}
*/
var minDistance = (word1, word2) => {
let lenA = word1.length;
let lenB = word2.length;
let d = createMatrix(lenB + 1, lenA + 1);
for (let i = 0; i <= lenA; i++) {
d[i][0] = i;
}
for (let i = 0; i <= lenB; i++) {
d[0][i] = i;
}
for (let i = 1; i <= lenA; i++) {
for (let j = 1; j <= lenB; j++) {
if (word1[i - 1] == word2[j - 1]) {
d[i][j] = d[i - 1][j - 1];
} else {
d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + 1);
}
}
}
return d[lenA][lenB];
}
let createMatrix = (rowNum, colNum) => {
let matrix = [];
matrix.length = colNum;
for (let i = 0; i < matrix.length; i++) {
matrix[i] = [];
matrix[i].length = rowNum;
matrix[i].fill(0);
}
return matrix
}
let a = "abcde";
let b = "abcd";
console.log(minDistance(a, b));