日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

删除两个字符串中的特定字符使其相等,统计删除的字符的ASCII和

發(fā)布時間:2024/4/17 编程问答 31 豆豆
生活随笔 收集整理的這篇文章主要介紹了 删除两个字符串中的特定字符使其相等,统计删除的字符的ASCII和 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

為什么80%的碼農(nóng)都做不了架構(gòu)師?>>> ??

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].

解決:

① ?動態(tài)規(guī)劃,難點在于想出將兩個字符串刪除到相同的過程。

二維數(shù)組dp[i][j]代表字符串1前i個字符和字符串2前j個字符實現(xiàn)相同所需要刪除的ASCII value

有三種方法可以到達dp[i][j]:

  • dp[i - 1][j] + str1[i]:由于從dp[i - 1][j]到dp[i][j]是多考慮了str1的一個字符,但是str2字符數(shù)沒變,所以要想相同,必須刪除str1[i],考慮value的話就是加上str1[i];
  • dp[i][j - 1] + str1[j]:對應(yīng)于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];
? ? }
}

轉(zhuǎn)載于:https://my.oschina.net/liyurong/blog/1607624

總結(jié)

以上是生活随笔為你收集整理的删除两个字符串中的特定字符使其相等,统计删除的字符的ASCII和的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。