删除两个字符串中的特定字符使其相等,统计删除的字符的ASCII和
為什么80%的碼農都做不了架構師?>>> ??
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];
? ? }
}
轉載于:https://my.oschina.net/liyurong/blog/1607624
總結
以上是生活随笔為你收集整理的删除两个字符串中的特定字符使其相等,统计删除的字符的ASCII和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Nginx+SSL+Tomcat+CDN
- 下一篇: 使用mybatis generator