Question

Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 the same, where in each step you can delete one character in either string.

Example 1:

Input: "sea", "eat"
Output: 2
Explanation: You need one step to make "sea" to "ea" and another step to make "eat" to "ea".

Note:

  • The length of given words won’t exceed 500.
  • Characters in given words can only be lower-case letters.

Solution:

  • Method 1: dp[i][j]: the minimum step for have same string for s[0:i] and t[0: j] AC 70.05%
    • Initialization: dp[0][0] = 0. Nothing need to do.
    • dp[0][i] = i, dp[i][0] = i. Remove all characters from a string to reach a empty one.
    • State transfer function:
      • if characters are the same: dp[i][j] = dp[i - 1][j - 1]
      • if not the same:
        • remove both of current characters: dp[i - 1][j - 1] + 2
        • remove one character from either string: dp[i - 1][j] + 1 && dp[i][j - 1] + 1.
        • select the minimum from the three methods.
            class Solution {
            public int minDistance(String word1, String word2) {
            char[] arr1 = word1.toCharArray(), arr2 = word2.toCharArray();
            int len1 = arr1.length, len2 = arr2.length;
            int[][] dp = new int[len1 + 1][len2 + 1];
            dp[0][0] = 0;
            for(int i = 1; i <= len1; i++)
            dp[i][0] = i;
            for(int i = 1; i <= len2; i++)
            dp[0][i] = i;
            for(int i = 1; i <= len1; i++){
            for(int j = 1; j <= len2; j++){
                if(arr1[i - 1] == arr2[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[len1][len2];
            }
            }