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.

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. 先计算最长公共子序列的长度
  2. 根据长度,通过回溯求出最长公共子序列

我们用一个二维数组存储Xi与Yj的最长公共子序列的长度,则有递推公式:

同理,我们可以根据这个递推公式用一个二维数组来存储LCS的ASCII码,最后用两个字符串的ASCII码分别减去这个值求和就可以了。

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
26
27
28
29
30
31
32
33
34
var minimumDeleteSum = function(s1, s2) {
let len1 = s1.length
let len2 = s2.length
let result = []
for (let i=0; i<=len1; i++) {
result[i] = []
for (let j=0; j<=len2; j++) {
result[i][j] = 0
}
}

for(let i=0; i<len1; i++){
for (let j=0; j<len2; j++){
if(s1[i]==s2[j]){
result[i+1][j+1] = result[i][j] + s1.charCodeAt(i)
}
else{
result[i+1][j+1] = Math.max(result[i+1][j],result[i][j+1])
}

}
}
console.log(result)

let asc1 = 0
let asc2 = 0
for (let i=0; i<len1; i++){
asc1 += s1.charCodeAt(i)
}
for (let i=0; i<len2; i++){
asc2 += s2.charCodeAt(i)
}
return asc1+asc2-2*result[len1][len2]
};