单词在匹配牌照中的字母时不区分大小写,比如牌照中的 "P"
依然可以匹配单词中的 "p"
字母。
我们保证一定存在一个最短完整词。当有多个单词都符合最短完整词的匹配条件时取单词列表中最靠前的一个。
牌照中可能包含多个相同的字符,比如说:对于牌照 "PP"
,单词 "pair"
无法匹配,但是 "supper"
可以匹配。
示例 1:
输入:licensePlate = "1s3 PSt", words = ["step", "steps", "stripe", "stepple"] 输出:"steps" 说明:最短完整词应该包括 "s"、"p"、"s" 以及 "t"。对于 "step" 它只包含一个 "s" 所以它不符合条件。同时在匹配过程中我们忽略牌照中的大小写。
示例 2:
输入:licensePlate = "1s3 456", words = ["looks", "pest", "stew", "show"] 输出:"pest" 说明:存在 3 个包含字母 "s" 且有着最短长度的完整词,但我们返回最先出现的完整词
方法一:简单暴力的解决方法:遍历个字符匹配
耗时大
class Solution:
def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
licen = []
licensePlate = licensePlate.lower()
for i in list(licensePlate):
if i.isalpha():
licen.append(i)
li = ''
for word in words:
count = 0
w = list(word)
for i in licen:
if i.isalpha():
if i in w:
w.remove(i)
count += 1
else:
break
if count == len(licen):
if li == '':
li = word
else:
if len(li) > len(word):
li = word
return li
方法二:统计字符出现的频率,判断一个字典是否为另一个字典的子集
class Solution:
def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
licensePlate = licensePlate.lower()
#统计字符出现的频率
count = {}
for i in list(licensePlate):
if i.isalpha():
if i in count:
count[i] += 1
else:
count[i] = 1
word_result = "2"*1000
for word in words:
word_count = {}
for i in list(word):
if i in word_count:
word_count[i] += 1
else:
word_count[i] = 1
sign = True
for key, values in count.items():
if key not in word_count or word_count[key] < values:
sign = False
break
if sign:
if len(word) < len(word_result):
word_result = word
return word_result