712 Minimum ASCII Delete Sum for Two Strings

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

1
2
3
4
5
6
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.
1
2
3
4
5
6
7
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].

题目大意

给定两个字符串,删除其中一些字符使得两个字符相等。
删除字符ASCII和最小的。

解题思路

动态规划
使用数组dp记录s1i项ASCII和。
遍历s2, 使用tmp记录删除字符ASCII和最小。添加规则为:

1
2
3
4
5
6
7
如果相等,则tmp 添加dp[j - 1],
如果不相等,则有两种选择。第一种:删除s2[i - 1]ASCII再加上前i - 1项内最小的ASCII和;第二种:删除s1[j - 1]再加上前j - 1项内最小的ASCII和
if s2[i - 1] == s1[j - 1] {
tmp.append(dp[j - 1])
}else {
tmp.append(min(dp[j] + Int(s2[i - 1].value), tmp[j - 1] + Int(s1[j - 1].value)))
}

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
func minimumDeleteSum(_ s1: String, _ s2: String) -> Int {
var dp = [0]
var arr1 = Array(s1.unicodeScalars)
var arr2 = Array(s2.unicodeScalars)
for char in s1.unicodeScalars {
dp.append(dp.last! + Int(char.value))
}
for i in 1...arr2.count {
var tmp = [dp[0] + Int(arr2[i - 1].value)]
for j in 1...arr1.count {
if arr2[i - 1] == arr1[j - 1] {
tmp.append(dp[j - 1])
}else {
tmp.append(min(dp[j] + Int(arr2[i - 1].value), tmp[j - 1] + Int(arr1[j - 1].value)))
}
}
dp = tmp
}
return dp.last!
}
}
0%