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:
1
2
3
4
5
6
7
8
9
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.
To make two strings equal with the minimum ASCII delete sum, we use dynamic programming to track the minimum cost for each substring pair. At each step, we can delete a character from either string or keep matching characters.
classSolution {
publicintminimumDeleteSum(String s1, String s2) {
int n = s1.length(), m = s2.length();
int[][] dp =newint[n+1][m+1];
for (int i = n-1; i >= 0; i--)
dp[i][m]= dp[i+1][m]+ s1.charAt(i);
for (int j = m-1; j >= 0; j--)
dp[n][j]= dp[n][j+1]+ s2.charAt(j);
for (int i = n-1; i >= 0; i--) {
for (int j = m-1; j >= 0; j--) {
if (s1.charAt(i) == s2.charAt(j))
dp[i][j]= dp[i+1][j+1];
else dp[i][j]= Math.min(s1.charAt(i)+dp[i+1][j], s2.charAt(j)+dp[i][j+1]);
}
}
return dp[0][0];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
classSolution {
funminimumDeleteSum(s1: String, s2: String): Int {
val n = s1.length; val m = s2.length
val dp = Array(n+1) { IntArray(m+1) }
for (i in n-1 downTo 0)
dp[i][m] = dp[i+1][m] + s1[i].code
for (j in m-1 downTo 0)
dp[n][j] = dp[n][j+1] + s2[j].code
for (i in n-1 downTo 0) {
for (j in m-1 downTo 0) {
if (s1[i] == s2[j])
dp[i][j] = dp[i+1][j+1]
else dp[i][j] = minOf(s1[i].code+dp[i+1][j], s2[j].code+dp[i][j+1])
}
}
return dp[0][0]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
defminimumDeleteSum(s1: str, s2: str) -> int:
n, m = len(s1), len(s2)
dp = [[0]*(m+1) for _ in range(n+1)]
for i in range(n-1, -1, -1):
dp[i][m] = dp[i+1][m] + ord(s1[i])
for j in range(m-1, -1, -1):
dp[n][j] = dp[n][j+1] + ord(s2[j])
for i in range(n-1, -1, -1):
for j in range(m-1, -1, -1):
if s1[i] == s2[j]:
dp[i][j] = dp[i+1][j+1]
else:
dp[i][j] = min(ord(s1[i])+dp[i+1][j], ord(s2[j])+dp[i][j+1])
return dp[0][0]