python-leetcode-748. 最短补全词

748. 最短补全词 - 力扣(LeetCode)

可以使用 collections.Counter 统计 licensePlate 中的字母频次,然后遍历 words,找到第一个符合条件的最短单词。代码如下:

from collections import Counter

def shortest_completing_word(licensePlate: str, words: list) -> str:
    # 统计 licensePlate 中的字母频次
    count_lp = Counter(c.lower() for c in licensePlate if c.isalpha())
    
    # 按长度排序 words
    words.sort(key=len)
    
    for word in words:
        count_word = Counter(word)
        if all(count_word[c] >= count_lp[c] for c in count_lp):
            return word
    
    return ""  # 题目保证一定存在符合条件的单词

可以使用这个函数,传入 licensePlatewords,它会返回最短补全词。例如:

licensePlate = "aBc 12c"
words = ["abccdef", "caaacab", "cbca"]
print(shortest_completing_word(licensePlate, words))

输出:

"cbca"

这种方法保证了正确性和效率,先统计 licensePlate,再逐个检查单词是否符合条件,并优先返回最短的符合条件的单词。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值