Leetcode 583-两个字符串的删除操作

注意初始化和状态转移方程式

class Solution {
    //1.dp[i][j]:使得word1[0:i-1]和word2[0:j-1]相同的操作
    //2.word1[i-1]==word2[j-1] dp[i][j]=dp[i-1][j-1]
    //word1[i]-1!=word2[j-1] dp[i][j]=Math.min(dp[i-1][j]+1,dp[i-1][j-1]+2,dp[i][j-1])(删word1(word1[i-2]==word2[j-1]),两个都删,删word2)
    //3.dp[i][0]=i,dp[0][j]=j
    //4.遍历顺序,正序
    //5.返回dp[len1][len2]
    public int minDistance(String word1, String word2) {
        int[][] dp = new int[word1.length()+1][word2.length()+1];
         for(int i=0;i<=word1.length();i++){
             dp[i][0]=i;
        }
        for(int j=1;j<=word2.length();j++){
             dp[0][j]=j;
         }
        //注意遍历范围
        for(int i=1;i<=word1.length();i++){
          for(int j=1;j<=word2.length();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-1][j]+1,dp[i][j-1]+1));
          }
        }
        return dp[word1.length()][word2.length()];
    }
}

你可能感兴趣的:(算法,算法)