zoukankan      html  css  js  c++  java
  • 712. Minimum ASCII Delete Sum for Two Strings

    问题

    给定两个字符串,删除字符使得两个字符串相等,如何删使得删除的字符的ASCII和最小。

    Input: s1 = "sea", s2 = "eat"
    Output: 231
    Explanation: 115(s) + 116(t) = 231

    思路

    用dp[i][j]表示s1[:i]和s2[:j]之间的解。
    如果s1[i-1] == s2[j-1],dp[i][j] = dp[i-1][j-1]。两字符相等,不需要删除,等于之前的值。
    否则,dp[i][j] = min(dp[i-1][j]+ s1[i-1], dp[i][j-1] + s2[j-1])。不等,需要删除,在之前的结果基础上,计算删s1字符的代价和删s2字符的代价哪个小。

    时间复杂度O(n*m),空间复杂度O(n*m)

    代码

    class Solution(object):
        def minimumDeleteSum(self, s1, s2):
            """
            :type s1: str
            :type s2: str
            :rtype: int
            """
            dp = [[0 for _ in range(len(s2)+1)] for _ in range(len(s1)+1)]
            for i in range(1,len(s2)+1):
                dp[0][i] = dp[0][i-1] + ord(s2[i-1])
            for j in range(1,len(s1)+1):
                dp[j][0] = dp[j-1][0] + ord(s1[j-1])
            for i in range(1,len(s1)+1):
                for j in range(1,len(s2)+1):
                    if(s1[i-1]==s2[j-1]):
                        dp[i][j] = dp[i-1][j-1]
                    else:
                        dp[i][j] = min(dp[i-1][j]+ord(s1[i-1]), dp[i][j-1]+ord(s2[j-1]))
            return dp[len(s1)][len(s2)]
    

    相关知识

    ord('a') == 97  #获取字符对应的ASCII码
    
    chr(97) == 'a'  #获取ASCII码对应的字符
    chr(0x61) == 'a' #可以输入十六进制
    
    hex(97) == '0x61'  #获取整数对应的十六进制字符串
    
    oct(97) == '0141'  #获取整数对应的八进制字符串
    

    类似题目

    72. Edit Distance

  • 相关阅读:
    Swift
    美国绿卡
    H-1-B签证简介
    托福、雅思和GRE的区别
    使用fdisk命令对linux硬盘进行操作
    Welcome to Workrave
    Installing patches on an ESXi 5.x by the command
    How to install VIB on VMware ESXi
    Robocopy用法
    Location of ESXi 5.1 log files
  • 原文地址:https://www.cnblogs.com/liaohuiqiang/p/9756753.html
Copyright © 2011-2022 走看看