题目
给你一个字符串
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)