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
.[97, 122]
.给定两个字符串s1,s2,找到删除字符的最低ASCII总和,使两个字符串相等。
/**
* @param {string} s1
* @param {string} s2
* @return {number}
*/
var minimumDeleteSum = function (s1, s2) {
let lenA = s1.length;
let lenB = s2.length;
let dp = createMatrix(lenB + 1, lenA + 1);
for (let i = 1; i <= lenA; i++) {
dp[i][0] = dp[i - 1][0] + s1[i - 1].charCodeAt();
}
for (let i = 1; i <= lenB; i++) {
dp[0][i] = dp[0][i - 1] + s2[i - 1].charCodeAt();
}
for (let i = 1; i <= lenA; i++) {
for (let j = 1; j <= lenB; j++) {
let last = dp[i - 1][j - 1];
let s1LastCode = s1[i - 1].charCodeAt();
let s2LastCode = s2[j - 1].charCodeAt();
if (s1[i - 1] != s2[j - 1]) {
last += s1LastCode + s2LastCode;
}
dp[i][j] = Math.min(last, dp[i - 1][j] + s1LastCode, dp[i][j - 1] + s2LastCode);
}
}
printMatrix(dp);
return dp[lenA][lenB];
};
let createMatrix = (rowNum, colNum) => {
let matrix = [];
matrix.length = colNum;
for (let i = 0; i < matrix.length; i++) {
matrix[i] = [];
matrix[i].length = rowNum;
matrix[i].fill(0);
}
return matrix
}
let printMatrix = (matrix) => {
let str = "";
for (let i in matrix) {
for (let j in matrix[i]) {
str += matrix[i][j] + ","
}
str += " ";
}
console.log(str);
}
let a = "abcde";
let b = "abcd";
console.log(minimumDeleteSum(a, b));