Re: [闲聊] 每日LeetCode

楼主: Rushia (みけねこ的鼻屎)   2023-07-31 23:50:58
https://leetcode.com/problems/minimum-ascii-delete-sum-for-two-strings/description/
712. Minimum ASCII Delete Sum for Two Strings
给你两个字串 s1 和 s2,求出被删除的字符之最小ASCII和,可以使 s1 和 s2 两字串相
等。
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.
思路:
1.这题基本上就编辑距离的变种,作法是求 LCS 的 DP 作法,我们先称他为MDS。
2.定义 dp[i][j] 为 s1 长度为 i 且 s2 长度为 j 的最小删除和,先初始化第一行第
一列,对于长度为 0 的字串来说,MDS 一定是不为 0 的那个字串的所有字符和,因
为只有删掉全部字符才会等于空字串,所以就按照长度累加ASCII值就好。
3.初始化完 DP 的第一行和第一列后,我们可以分成两种 CASE:
s1[i] = s2[j]:表示当前两个字串的字符相同不需删除,所以他的长度为上一个最小
s1[i] != s2[j]: dp[i][j]可能是长度为 dp[i-1][j] 或 dp[i][j-1] 的 MDS 删除其
中一个字符获得,取较小的。
4.dp更新完全部长度就完事
Java Code:

Links booklink

Contact Us: admin [ a t ] ucptt.com