

可以使用 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 "" # 题目保证一定存在符合条件的单词
可以使用这个函数,传入 licensePlate 和 words,它会返回最短补全词。例如:
licensePlate = "aBc 12c"
words = ["abccdef", "caaacab", "cbca"]
print(shortest_completing_word(licensePlate, words))
输出:
"cbca"
这种方法保证了正确性和效率,先统计 licensePlate,再逐个检查单词是否符合条件,并优先返回最短的符合条件的单词。
2257

被折叠的 条评论
为什么被折叠?



