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()];
      }
    };
  • 相关阅读:
    hdu 2669 Romantic 扩展欧几里德
    fzu 1759 Super A^B mod C 大数幂取模
    POJ2429 SCU2106 GCD & LCM Inverse
    spring和hibernate整合时报sessionFactory无法获取默认Bean Validation factory
    SSH Secure Shell Client安装和使用
    乔布斯在斯坦福大学的演讲
    Java 事件处理机制
    Java 网络编程 简单接触TCP
    设计模式 职责链模式
    设计模式 命令模式
  • 原文地址:https://www.cnblogs.com/ethanhong/p/10207995.html
Copyright © 2011-2022 走看看