leetcode72 edit distance

Insert picture description here
The value in the lower right corner is the final required value
The idea
of dynamic programming

Definition dp[i][j]
21. dp[i][j] represents the first i characters in word1, transformed to the first j characters in word2, the shortest number of operations
required 22. Need to consider whether word1 or word2 does not have a letter , That is, all add/delete situations, so reserve dp[0][j] and dp[i][0]

State transition
31. Increase, dp[i][j] = dp[i][j-1] + 1
32. Delete, dp[i][j] = dp[i-1][j] + 1
33. Change, dp[i][j] = dp[i-1][j-1] + 1
34. Calculate in order, when calculating dp[i][j], dp[i-1][j], dp[i][j-1], dp[i-1][j-1] have been determined
35. With the addition, deletion and modification of these three operations, the corresponding dp is required to increase the number of operations by one, and take the smallest of the three
36. If these two letters happen to be the same word1[i-1] = word2[j-1], then you can directly refer to dp[i-1][j-1] without adding one to the operation

Author: ikaruga
link: https: //leetcode-cn.com/problems/edit-distance/solution/edit-distance-by-ikaruga/
Source: stay button (LeetCode)
copyright reserved by the authors. For commercial reprints, please contact the author for authorization, and for non-commercial reprints, please indicate the source.

Insert picture description here
Bottom-down:

public static int minDistance(String word1,String word2){
    
    
        int n1 = word1.length();
        int n2 = word2.length();

        int[][] dp = new int[n1+1][n2+1];

       //初始化 如果i或j两者中其中一个为零,则对word1一直执行删除操作或一直执行插入操作,且此时不能使用该关系式
        for (int j = 1;j <= n2;j++){
    
    
            dp[0][j] = dp[0][j-1]+1;
        }
        for (int i = 1;i <= n1;i++){
    
    
            dp[i][0] = dp[i-1][0]+1;
        }

        //将从0-i的字符转换成0-j的字符
        for (int i = 1;i <= n1;i++){
    
    
            for (int j = 1;j <= n2;j++){
    
    
                //如果word1[i]和word2[j]相等,第i个字符对应下标是i-1;
                if (word1.charAt(i-1) == word2.charAt(j-1)){
    
    
                    dp[i][j] = dp[i-1][j-1];
                }else {
    
    
                    //分别是删除,插入,替换操作。
                    dp[i][j] = Math.min(Math.min(dp[i-1][j-1],dp[i][j-1]),dp[i-1][j])+1;
                }
            }
        }
        return dp[n1][n2];
    }

Original link

Guess you like

Origin blog.csdn.net/weixin_45773632/article/details/109500405