|
| 1 | +package com.fishercoder.solutions; |
| 2 | + |
| 3 | +/** |
| 4 | + * 712. Minimum ASCII Delete Sum for Two Strings |
| 5 | + * |
| 6 | + * Given two strings s1, s2, find the lowest ASCII sum of deleted characters to make two strings equal. |
| 7 | +
|
| 8 | + Example 1: |
| 9 | + Input: s1 = "sea", s2 = "eat" |
| 10 | + Output: 231 |
| 11 | + Explanation: Deleting "s" from "sea" adds the ASCII value of "s" (115) to the sum. |
| 12 | + Deleting "t" from "eat" adds 116 to the sum. |
| 13 | + At the end, both strings are equal, and 115 + 116 = 231 is the minimum sum possible to achieve this. |
| 14 | +
|
| 15 | + Example 2: |
| 16 | + Input: s1 = "delete", s2 = "leet" |
| 17 | + Output: 403 |
| 18 | + Explanation: Deleting "dee" from "delete" to turn the string into "let", |
| 19 | + adds 100[d]+101[e]+101[e] to the sum. Deleting "e" from "leet" adds 101[e] to the sum. |
| 20 | + At the end, both strings are equal to "let", and the answer is 100+101+101+101 = 403. |
| 21 | + If instead we turned both strings into "lee" or "eet", we would get answers of 433 or 417, which are higher. |
| 22 | +
|
| 23 | + Note: |
| 24 | + 0 < s1.length, s2.length <= 1000. |
| 25 | + All elements of each string will have an ASCII value in [97, 122]. |
| 26 | + */ |
| 27 | +public class _712 { |
| 28 | + public static class Solution1 { |
| 29 | + //credit: https://leetcode.com/articles/minimum-ascii-delete-sum-for-two-strings/ |
| 30 | + public int minimumDeleteSum(String s1, String s2) { |
| 31 | + int[][] dp = new int[s1.length()+1][s2.length()+1]; |
| 32 | + |
| 33 | + for (int i = s1.length()-1; i >= 0; i--) { |
| 34 | + dp[i][s2.length()] = dp[i+1][s2.length()] + s1.codePointAt(i); |
| 35 | + } |
| 36 | + |
| 37 | + for (int j = s2.length()-1; j >= 0; j--) { |
| 38 | + dp[s1.length()][j] = dp[s1.length()][j+1] + s2.codePointAt(j); |
| 39 | + } |
| 40 | + |
| 41 | + for (int i = s1.length() - 1; i >= 0; i--) { |
| 42 | + for (int j = s2.length()-1; j >= 0; j--) { |
| 43 | + if (s1.charAt(i) == s2.charAt(j)) { |
| 44 | + dp[i][j] = dp[i+1][j+1]; |
| 45 | + } else { |
| 46 | + dp[i][j] = Math.min(dp[i+1][j] + s1.codePointAt(i), dp[i][j+1] + s2.codePointAt(j)); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return dp[0][0]; |
| 52 | + } |
| 53 | + } |
| 54 | +} |
0 commit comments