zoukankan      html  css  js  c++  java
  • LC 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.
    

     

    Note:

    • 0 < s1.length, s2.length <= 1000.
    • All elements of each string will have an ASCII value in [97, 122].

    两个字符串最长子序列。

    Runtime: 12 ms, faster than 76.47% of C++ online submissions for Minimum ASCII Delete Sum for Two Strings.

    #include <iostream>
    #include <string>
    #include <string.h>
    using namespace std;
    class Solution {
    public:
      int minimumDeleteSum(string s1, string s2) {
        int dp[s1.size()+1][s2.size()+1];
        memset(dp, 0, sizeof(dp));
        int sum = 0;
        for(int i=0; i<s1.size(); i++){
          sum += (int)s1[i];
          for(int j=0; j<s2.size(); j++){
            if(s1[i] == s2[j]) {
              dp[i+1][j+1] = dp[i][j] + (int)s1[i];
            }else {
              dp[i+1][j+1] = max(dp[i+1][j], dp[i][j+1]);
            }
          }
        }
        for(int i=0; i<s2.size(); i++){
          sum += (int)s2[i];
        }
        return sum - 2*dp[s1.size()][s2.size()];
      }
    };
  • 相关阅读:
    2013111 小有收获
    2013112 周末
    js return的使用 Yannis
    java与js的split方法 Yannis
    javaScript 实时获取系统时间 Yannis
    java中奇偶数的判断 Yannis
    将Tomcat添加至开机自启动 Yannis
    java除0问题探究 Yannis
    linux安装问题 Yannis
    java之Struts2实现用户登录过滤 Yannis
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10207995.html
Copyright © 2011-2022 走看看