Leetcode712. 计算两个字符串删除任意字符后使二者相等的最小删除字符和

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python代码如下: ```python def compare_str(s1, s2, order): """ 比较两个字符串的大小,如果相等则按照原始顺序进行比较 :param s1: 字符串1 :param s2: 字符串2 :param order: 原始顺序列表 :return: 如果s1小于s2,则返回True,否则返回False """ if s1 == s2: return order.index(s1) < order.index(s2) i = 0 while i < min(len(s1), len(s2)): if s1[i] != s2[i]: return order.index(s1[i]) < order.index(s2[i]) i += 1 return len(s1) < len(s2) def sort_words(words, order): """ 对words按照order排序 :param words: 待排序字符串列表 :param order: 排序表 :return: 排序后的字符串列表 """ for i in range(len(words)): for j in range(i + 1, len(words)): if not compare_str(words[i], words[j], order): words[i], words[j] = words[j], words[i] return words def sort_alien_dictionary(words, order): """ 对外部接口,按照order对words进行排序 :param words: 待排序字符串列表 :param order: 排序表 :return: 排序后的字符串列表 """ # 制作出排序表 order_dict = {} for i in range(len(order)): order_dict[order[i]] = i # 对字符串进行切割,利用一个二维数组来存放数据 word_list = [] for word in words: word_list.append(list(word)) # 按照题目意思对二维数组进行顺序的教换 for i in range(len(word_list[0])): for j in range(1, len(word_list)): if i >= len(word_list[j]): return [] if order_dict[word_list[j - 1][i]] > order_dict[word_list[j][i]]: word_list[j - 1], word_list[j] = word_list[j], word_list[j - 1] break # 重新拼装并输出 res = [] for word in word_list: res.append("".join(word)) return res ``` 测试代码如下: ```python words = ["hello", "leetcode", "hell", "panda", "dog"] order = "hlabcdefgijkmnopqrstuvwxyz" print(sort_alien_dictionary(words, order)) # ['hell', 'hello', 'leetcode', 'dog', 'panda'] words = ["z", "x", "z"] order = "abcdefghijklmnopqrstuvwxyz" print(sort_alien_dictionary(words, order)) # [] words = ["apple", "app"] order = "abcdefghijklmnopqrstuvwxyz" print(sort_alien_dictionary(words, order)) # ['app', 'apple'] words = ["app", "apple"] order = "abcdefghijklmnopqrstuvwxyz" print(sort_alien_dictionary(words, order)) # ['app', 'apple'] ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值