【748】最短补全词

题目

给你一个字符串 licensePlate 和一个字符串数组 words ,请你找出并返回 words 中的 最短补全词 。

补全词 是一个包含 licensePlate 中所有字母的单词。

输入:licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"]
输出:"steps"
解释:最短补全词应该包括 "s"、"p"、"s"(忽略大小写) 以及 "t"。
"step" 包含 "t"、"p",但只包含一个 "s",所以它不符合条件。
"steps" 包含 "t"、"p" 和两个 "s"。
"stripe" 缺一个 "s"。
"stepple" 缺一个 "s"。
因此,"steps" 是唯一一个包含所有字母的单词,也是本例的答案。

我的

提取字母并转化成小写;字典记录每个字母出现的次数;对words进行排序,最早的符合条件的就是那个word;遍历每个word的每个字母,如果出现在record字典里,就计数-1,当计数=0时,删掉这个key;如果最后record为空,则返回这个word。

注意字典更改的引用和复制。

class Solution:
    def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
        licensePlate = "".join([i for i in licensePlate if i.isalpha()]).lower()
        record = {}
        for i in licensePlate:
            if i not in record.keys():
                record[i] = 1
            else:
                record[i] += 1
        
        words.sort(key=lambda i:len(i))

        for word in words:
            if len(word) >= len(licensePlate):
                record2 = record.copy()
                for j in word:
                    if j in record2.keys():
                        record2[j] -= 1
                        if record2[j] == 0:
                            record2.pop(j)
                if record2 == {}:
                    return word

官方的

python3 Counter类(计数器) - Water~ - 博客园

counter直接返回的就是record{}。

Python字典加减操作_Code忆旧录-CSDN博客_python字典相减

输出会忽略掉结果为零或者小于零的计数。

对字典的相关操作更加熟悉了

class Solution:
    def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
        cnt = Counter(ch.lower() for ch in licensePlate if ch.isalpha())
        return min((word for word in words if not cnt - Counter(word)), key=len)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值