Minimum ASCII Delete Sum for Two Strings
问题:
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]
.
解决:
① 动态规划,难点在于想出将两个字符串删除到相同的过程。
二维数组dp[i][j]代表字符串1前i个字符和字符串2前j个字符实现相同所需要删除的ASCII value;
有三种方法可以到达dp[i][j]:
- dp[i - 1][j] + str1[i]:由于从dp[i - 1][j]到dp[i][j]是多考虑了str1的一个字符,但是str2字符数没变,所以要想相同,必须删除str1[i],考虑value的话就是加上str1[i];
- dp[i][j - 1] + str1[j]:对应于1,这个是多考虑str2的一个字符,所以要删除str2[j]
- dp[i - 1][j - 1] + a,这里是考虑两个str都加了一个,所以str1[i] =str2[j]时,a=0;str1[i] != str2[j]时,两个都要删除,a=str1[i] +str2[j]
这三种情况每次比较出最小的来,最后返回dp[str1.length][str2.length]
class Solution { //49ms
public int minimumDeleteSum(String s1, String s2) {
int m = s1.length();
int n = s2.length();
int[][] dp = new int[m + 1][n + 1];
for (int i = 1;i <= m;i ++){
dp[i][0] = dp[i - 1][0] + s1.charAt(i - 1);
}
for (int i = 1;i <= n;i ++){
dp[0][i] = dp[0][i - 1] + s2.charAt(i - 1);
}
for (int i = 1;i <= m;i ++){
for (int j = 1;j <= n;j ++){
int a = (s1.charAt(i - 1) == s2.charAt(j - 1)) ? 0 : s1.charAt(i - 1) + s2.charAt(j - 1);
dp[i][j] = Math.min(dp[i - 1][j - 1] + a,
Math.min(dp[i - 1][j] + s1.charAt(i - 1),dp[i][j - 1] + s2.charAt(j - 1)));
}
}
return dp[m][n];
}
}