leetcode--Edit Distance

短命女 2021-10-25 12:40 411阅读 0赞

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

  1. public class Solution {
  2. /**
  3. * dynamic programming. Very basic problem.
  4. * @param word1 -String
  5. * @param word2 -String
  6. * @return int -number of modifications to change word1 to word2
  7. * @author Averill Zheng
  8. * @version 2014-06-24
  9. * @since JDK 1.7
  10. */
  11. public int minDistance(String word1, String word2) {
  12. int column = word1.length(), row = word2.length();
  13. if(row == 0)
  14. return column;
  15. if(column == 0)
  16. return row;
  17. int[][] changes = new int[row + 1][column + 1];
  18. for(int i = 0; i < column + 1; ++i)
  19. changes[0][i] = i;
  20. for(int i = 0; i < row + 1; ++i)
  21. changes[i][0] = i;
  22. for(int i = 1; i < row + 1; ++i){
  23. for(int j = 1; j < column + 1; ++j){
  24. if(word1.charAt(j - 1) == word2.charAt(i - 1))
  25. changes[i][j] = Math.min(changes[i - 1][j - 1], 1 + Math.min(changes[i - 1][j],
  26. changes[i][j - 1]));
  27. else
  28. changes[i][j] = Math.min(1 + changes[i - 1][j - 1], 1 + Math.min(changes[i - 1][j],
  29. changes[i][j - 1]));
  30. }
  31. }
  32. return changes[row][column];
  33. }
  34. }

  

转载于:https://www.cnblogs.com/averillzheng/p/3807282.html

发表评论

表情:
评论列表 (有 0 条评论,411人围观)

还没有评论,来说两句吧...

相关阅读