当前位置:   article > 正文

力扣HOT100 - 72. 编辑距离

力扣HOT100 - 72. 编辑距离

解题思路:

动态规划

  1. class Solution {
  2. public int minDistance(String word1, String word2) {
  3. int n1 = word1.length();
  4. int n2 = word2.length();
  5. int[][] dp = new int[n1 + 1][n2 + 1];
  6. for (int j = 1; j <= n2; j++) dp[0][j] = dp[0][j - 1] + 1;
  7. for (int i = 1; i <= n1; i++) dp[i][0] = dp[i - 1][0] + 1;
  8. for (int i = 1; i <= n1; i++) {
  9. for (int j = 1; j <= n2; j++) {
  10. if (word1.charAt(i - 1) == word2.charAt(j - 1)) dp[i][j] = dp[i - 1][j - 1];
  11. else dp[i][j] = Math.min(Math.min(dp[i - 1][j - 1], dp[i][j - 1]), dp[i - 1][j]) + 1;
  12. }
  13. }
  14. return dp[n1][n2];
  15. }
  16. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小小林熬夜学编程/article/detail/611744
推荐阅读
相关标签
  

闽ICP备14008679号