712. Minimum ASCII Delete Sum for Two Strings

Question

Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal.

Example 1:

Input: s1 = "sea", s2 = "eat"
Output: 231
Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum.
Deleting "t" from "eat" adds 116 to the sum.
At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this.

Example 2:

Input: s1 = "delete", s2 = "leet"
Output: 403
Explanation: Deleting "dee" from "delete" to turn the string into "let",
adds 100[d]+101[e]+101[e] to the sum.  Deleting "e" from "leet" adds 101[e] to the sum.
At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403.
If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher.

Note:

  • 0 < s1.length, s2.length <= 1000.
  • All elements of each string will have an ASCII value in [97, 122].

Solution:

  • Method 1: dp[i][j]: the minimum asc ii for have same string for s[0:i] and t[0: j] AC 97%
    • Initialization: dp[0][0] = 0. Nothing need to delete.
    • dp[0][i] = char at s2, dp[i][0] = char at s1. 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] + s1[i - 1] + s2[j - 1]
        • remove one character from either string: dp[i - 1][j] + s1[i - 1] && dp[i][j - 1] + s2[j - 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];
            }
            }
          
  1. 583. Delete Operation for Two Strings