当前位置:网站首页>[code Capriccio - dynamic planning] t583. Deleting two strings

[code Capriccio - dynamic planning] t583. Deleting two strings

2022-06-26 17:18:00 Not blogging

T583、 Deletion of two strings

Give two words word1 and word2 , Return makes word1 and word2 The same minimum number of steps required .
Every step You can delete a character from any string

Solution to the problem :
step1、dp[i][j] Express word1[0:i-1] and word2[0:j-1] To achieve equality , The minimum number of times an element needs to be deleted .
step2、 The recursive formula
When word1.charAt(i-1) == word2.charAt(j-1) When , be dp[i][j] = dp[i-1][j-1]
Fig1
https://www.programmercarl.com/0583.%E4%B8%A4%E4%B8%AA%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9A%84%E5%88%A0%E9%99%A4%E6%93%8D%E4%BD%9C.html

The second case is more complicated , When I write, I only consider dp[i][j-1]+1 This situation , It is equivalent to deleting only word2, So finally submit 159/1396

public int minDistance(String word1, String word2) {
    
        int n = word1.length();
        int m = word2.length();
        //  How to delete this logic 
        //  Last question  dp[i][j] Express word1[:i-1] 
        // word2[:j-1] The minimum number of steps 
        int[][] dp = new int[n+1][m+1];
        for(int j = 0; j <= m; j++){
    
            dp[0][j] = j;
        }
        for(int i = 0; i <= n; i++){
    
            dp[i][0] = i;
        }
        for(int i = 1; i <= n; i++){
    
            for(int j = 1; j <= m; j++){
    
                if(word1.charAt(i-1) == word2.charAt(j-1)){
    
                    dp[i][j] = dp[i-1][j-1];
                }else{
    
                    dp[i][j] = Math.min(dp[i-1][j-1]+2, Math.min(dp[i][j-1] + 1, dp[i-1][j]+1));
                }
            }
        }
        return dp[n][m];
    }
原网站

版权声明
本文为[Not blogging]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261656103168.html

随机推荐