72. Edit Distance 编辑距离

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)替换一个字符

  1. /**
  2. * @param {string} word1
  3. * @param {string} word2
  4. * @return {number}
  5. */
  6. var minDistance = (word1, word2) => {
  7. let lenA = word1.length;
  8. let lenB = word2.length;
  9. let d = createMatrix(lenB + 1, lenA + 1);
  10. for (let i = 0; i <= lenA; i++) {
  11. d[i][0] = i;
  12. }
  13. for (let i = 0; i <= lenB; i++) {
  14. d[0][i] = i;
  15. }
  16. for (let i = 1; i <= lenA; i++) {
  17. for (let j = 1; j <= lenB; j++) {
  18. if (word1[i - 1] == word2[j - 1]) {
  19. d[i][j] = d[i - 1][j - 1];
  20. } else {
  21. d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + 1);
  22. }
  23. }
  24. }
  25. return d[lenA][lenB];
  26. }
  27. let createMatrix = (rowNum, colNum) => {
  28. let matrix = [];
  29. matrix.length = colNum;
  30. for (let i = 0; i < matrix.length; i++) {
  31. matrix[i] = [];
  32. matrix[i].length = rowNum;
  33. matrix[i].fill(0);
  34. }
  35. return matrix
  36. }
  37. let a = "abcde";
  38. let b = "abcd";
  39. console.log(minDistance(a, b));







原文地址:https://www.cnblogs.com/xiejunzhao/p/8306154.html