• 712. Minimum ASCII Delete Sum for Two Strings 两个字符串的最小ASCII删除总和


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

给定两个字符串s1,s2,找到删除字符的最低ASCII总和,使两个字符串相等。
  1. /**
  2. * @param {string} s1
  3. * @param {string} s2
  4. * @return {number}
  5. */
  6. var minimumDeleteSum = function (s1, s2) {
  7. let lenA = s1.length;
  8. let lenB = s2.length;
  9. let dp = createMatrix(lenB + 1, lenA + 1);
  10. for (let i = 1; i <= lenA; i++) {
  11. dp[i][0] = dp[i - 1][0] + s1[i - 1].charCodeAt();
  12. }
  13. for (let i = 1; i <= lenB; i++) {
  14. dp[0][i] = dp[0][i - 1] + s2[i - 1].charCodeAt();
  15. }
  16. for (let i = 1; i <= lenA; i++) {
  17. for (let j = 1; j <= lenB; j++) {
  18. let last = dp[i - 1][j - 1];
  19. let s1LastCode = s1[i - 1].charCodeAt();
  20. let s2LastCode = s2[j - 1].charCodeAt();
  21. if (s1[i - 1] != s2[j - 1]) {
  22. last += s1LastCode + s2LastCode;
  23. }
  24. dp[i][j] = Math.min(last, dp[i - 1][j] + s1LastCode, dp[i][j - 1] + s2LastCode);
  25. }
  26. }
  27. printMatrix(dp);
  28. return dp[lenA][lenB];
  29. };
  30. let createMatrix = (rowNum, colNum) => {
  31. let matrix = [];
  32. matrix.length = colNum;
  33. for (let i = 0; i < matrix.length; i++) {
  34. matrix[i] = [];
  35. matrix[i].length = rowNum;
  36. matrix[i].fill(0);
  37. }
  38. return matrix
  39. }
  40. let printMatrix = (matrix) => {
  41. let str = "";
  42. for (let i in matrix) {
  43. for (let j in matrix[i]) {
  44. str += matrix[i][j] + ","
  45. }
  46. str += " ";
  47. }
  48. console.log(str);
  49. }
  50. let a = "abcde";
  51. let b = "abcd";
  52. console.log(minimumDeleteSum(a, b));




来自为知笔记(Wiz)


  • 相关阅读:
    IPC---信号量
    static的用法
    模拟对话框的实现
    Dom选择器使用与调试记录
    第一个javascript脚本
    javascript基础总汇
    overflow的量两种模式
    固定标签到页面
    固定标签到某个标签
    固定标签(position: fixed)
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/8306155.html
  • Copyright © 2020-2023  润新知