Baozi Leetcode solution 72. Edit Distance

Problem Statement

Given two words word1 and word2, find the minimum number of operations required to convert word1 to word2.

You have the following 3 operations permitted on a word:

  1. Insert a character
  2. Delete a character
  3. Replace a character

Example 1:

Input: word1 = "horse", word2 = "ros"
Output: 3
Explanation:
horse -> rorse (replace ‘h‘ with ‘r‘)
rorse -> rose (remove ‘r‘)
rose -> ros (remove ‘e‘)

Example 2:

Input: word1 = "intention", word2 = "execution"
Output: 5
Explanation:
intention -> inention (remove ‘t‘)
inention -> enention (replace ‘i‘ with ‘e‘)
enention -> exention (replace ‘n‘ with ‘x‘)
exention -> exection (replace ‘n‘ with ‘c‘)
exection -> execution (insert ‘u‘)

Problem link

Video Tutorial

You can find the detailed video tutorial here

Thought Process

Brute force sounds like really overkill because we have to list all the possible ways and it is exponential time complexity. On a high level, the recursion looks like

  • if cannot convert A to B, return -1 (the recursion termination function); if A == B, then return 0
  • try 3 different ways, insert, remove and replace, cut that character and continue the recursion. Compare the minimum of that 3 methods (exclude -1)

Edit distance is a classic Dynamic Programming (DP) problem, just like Coin Change Problem. It follows the DP template perfectly (asking for extreme values)

The mathematical induction function is

DP[i][j] is the minimum operations needed to convert String[0-i] to String[0-j]

Initial values: dp[0][j] = j and dp[i][0] = i

If (A[i] == B[j]) dp[i][j] =  dp[i-1][j-1]

Else min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) +1;

Solutions

DP

 1 public int minDistance(String word1, String word2) {
 2     if (word1 == null || word2 == null) return -1;
 3
 4     int l1 = word1.length();
 5     int l2 = word2.length();
 6
 7     if (l1 == 0 || l2 == 0) {
 8         return l1 == 0 ? l2 : l1;
 9     }
10
11     // A pattern for coding up DP, use extra array
12     // This could be further optimized into 2 arrays
13     int[][] lookup = new int[l1 + 1][l2 + 1];
14
15     // Note the initialization case here, for an empty string, it will take i to change with the current one
16     // initialize
17     for (int i = 0; i <= l2; i++) {
18         lookup[0][i] = i;
19     }
20
21     for (int i = 0; i <= l1;i++) {
22         lookup[i][0] = i;
23     }
24
25     /* mathematical induction function:
26      * dp[i][j] =  dp[i-1][j-1]   if (A[i] == B[j])
27        or = min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) +1;
28         dp[0][j] = j and dp[i][0] = i   */
29     // this is O(M*N) time and M*N space, space could be saved using 2 arrays
30     for (int i = 1; i <= l1; i++) {
31         for (int j = 1; j <= l2; j++) {
32             if (word1.charAt(i-1) == word2.charAt(j-1)) {
33                 lookup[i][j] = lookup[i-1][j-1];
34             } else {
35                 lookup[i][j] = Math.min(lookup[i-1][j], Math.min(lookup[i][j-1], lookup[i-1][j-1])) + 1;
36             }
37         }
38     }
39
40     return lookup[l1][l2];
41 }

Time Complexity: O(M*N) where M is word1 length and N is word2 length

Space Complexity: O(M*N) since we need an extra 2D array

References

原文地址:https://www.cnblogs.com/baozitraining/p/12114034.html

时间: 2024-11-02 02:18:08

Baozi Leetcode solution 72. Edit Distance的相关文章

【一天一道LeetCode】#72. Edit Distance

一天一道LeetCode 本系列文章已全部上传至我的github,地址:ZeeCoder's Github 欢迎大家关注我的新浪微博,我的新浪微博 欢迎转载,转载请注明出处 (一)题目 Given two words word1 and word2, find the minimum number of steps ?>required to convert word1 to word2. (each operation is counted as 1 step.) You have the f

LeetCode 72. Edit Distance Java

72.Edit Distance(编辑距离) 题目: 给定两个单词 word1 和 word2,计算出将 word1 转换成 word2 所使用的最少操作数 . 你可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个字符 思路: 多次选择试图得到最优解,那么考虑动态规划. 先假设word1有len1位,word2有len2位,建立数组step,step[i][j]就代表我们要将word1前 i 位转换为word2前 j 位的最少数量. 此时word1查找到第 i+1 位字母a,

72. Edit Distance &amp;&amp; 161. One Edit Distance

72. Edit Distance Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) You have the following 3 operations permitted on a word: a) Insert a characterb) Delete a c

刷题72. Edit Distance

一.题目说明 题目72. Edit Distance,计算将word1转换为word2最少需要的操作.操作包含:插入一个字符,删除一个字符,替换一个字符.本题难度为Hard! 二.我的解答 这个题目一点思路也没,就直接看答案了.用的还是dp算法,dp[n1+1][n2+1]中的dp[i][j]表示将word1的前i位,变为word2的前j位需要的步骤.注意第1行是空,第1列也是空. 1.第一行中,dp[0][i]表示空字符""到word2[0,...,i]需要编辑几次 2.第一列中,d

leetCode 72.Edit Distance (编辑距离) 解题思路和方法

Edit Distance Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) You have the following 3 operations permitted on a word: a) Insert a character b) Delete a char

leetcode 161. One Edit Distance 判断两个字符串是否是一步变换 --------- java

Given two strings S and T, determine if they are both one edit distance apart. 给定两个字符串,判断他们是否是一步变换得到的. 在这里需要注意几点: 1.不等于1的变换都要返回false(包括变换次数等于0). 2.还有很多细节需要注意. 方法如下: 1.直接判断:1)如果差值大于1,直接返回false.  2)如果长度相同,那么依次判断,是否只有一个字母不一样.  3)如果不一样,那么看是否是只是多出了一个字母. p

Baozi Leetcode solution 54: Sprial Matrix

Problem Statement  Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. Example 1: Input: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ] Output: [1,2,3,6,9,8,7,4,5] Example 2: Input: [ [1, 2, 3, 4], [5,

LeetCode 72 Edit Distance

Given two words word1 and word2, find the minimum number of steps required to convert word1 to word2. (each operation is counted as 1 step.) You have the following 3 operations permitted on a word: a) Insert a character b) Delete a character c) Repla

第十八周 Leetcode 72. Edit Distance(HARD) O(N^2)DP

Leetcode72 看起来比较棘手的一道题(列DP方程还是要大胆猜想..) DP方程该怎么列呢? dp[i][j]表示字符串a[0....i-1]转化为b[0....j-1]的最少距离 转移方程分三种情况考虑 分别对应三中操作 因为只需要三个值就可以更新dp[i][j] 我们可以把空间复杂度降低到O(n) Replace word1[i - 1] by word2[j - 1] (dp[i][j] = dp[i - 1][j - 1] + 1 (for replacement)); Delet