LeetCode brushing notes _72. Edit distance

The topic is from LeetCode

72. Edit distance

Other solutions or source code can be accessed: tongji4m3

description

Given two words word1 and word2, please calculate the minimum number of operations used to convert word1 to word2.

You can perform the following three operations on a word:

Insert a character
Delete a character
Replace a character

Example 1:

输入:word1 = "horse", word2 = "ros"
输出:3
解释:
horse -> rorse (将 'h' 替换为 'r')
rorse -> rose (删除 'r')
rose -> ros (删除 'e')

Example 2:

输入:word1 = "intention", word2 = "execution"
输出:5
解释:
intention -> inention (删除 't')
inention -> enention (将 'i' 替换为 'e')
enention -> exention (将 'n' 替换为 'x')
exention -> exection (将 'n' 替换为 'c')
exection -> execution (插入 'u')

Ideas

dp[i][j]代表将word1的前i-1个字符与word2的前j-1个字符转换的最小操作
返回dp[m][n]
初始化: dp[0][0]=0 dp[i][0]=i dp[0][j]=j
递推方程:
上边代表增加,左边代表删除,左上代表替换,因为可能不用替换
dp[i][j]=min(dp[i-1][j]+1,dp[i][j-1]+1,dp[i-1][j-1]+(word1[i-1]==word2[j-1] ? 0:1))

detail

  1. Pay attention to the operation of adding one when there is no match
  2. If it saves space, it can be represented by a one-dimensional array, which can be deduced from two dimensions. It should be noted that the initialization operation of the column changes during the derivation process, and the details of using a variable to store the upper left corner element

Code

public int minDistance(String word1, String word2)
{
    
    
    int m = word1.length(), n = word2.length();
    int[][] dp = new int[m + 1][n + 1];

    for (int i = 0; i < m + 1; i++) dp[i][0] = i;
    for (int j = 0; j < n + 1; j++) dp[0][j] = j;

    for (int i = 1; i < m + 1; i++)
    {
    
    
        for (int j = 1; j < n + 1; j++)
        {
    
    
            //look,需要+1,并且注意+1的时机
            dp[i][j] = Math.min(dp[i - 1][j] + 1,
                                Math.min(dp[i][j - 1] + 1, dp[i - 1][j - 1] + (word1.charAt(i - 1) == word2.charAt(j - 1) ? 0 : 1)));
        }
    }
    return dp[m][n];
}
//节约空间
public int minDistance(String word1, String word2)
{
    
    
    int m = word1.length(), n = word2.length();

    int[] dp = new int[n + 1];
    for (int j = 0; j < n + 1; j++) dp[j] = j;

    for (int i = 1; i < m + 1; i++)
    {
    
    
        int leftTop = dp[0];//look 记录左上角的值 注意和下面一条的顺序
        dp[0] = i;//look 不要忽略这里的初始化
        for (int j = 1; j < n + 1; j++)
        {
    
    
            int temp = dp[j];
            if (word1.charAt(i - 1) == word2.charAt(j - 1)) dp[j] = leftTop;
            else dp[j] = Math.min(dp[j], Math.min(dp[j - 1], leftTop)) + 1;
            leftTop = temp;
        }
    }
    return dp[n];
}

Complexity analysis

time complexity

O (N 2) O (N ^ 2) O ( N2)

Space complexity

O (N 2) O (N ^ 2) O ( N2 )Space optimization:O (N) O(N)O ( N )

Guess you like

Origin blog.csdn.net/weixin_42249196/article/details/108302317