LeetCode刷题记录——第748题(最短完整词)

版权声明:此BLOG为个人BLOG,内容均来自原创及互连网转载。最终目的为记录自己需要的内容或自己的学习感悟,不涉及商业用途,转载请附上原博客。 https://blog.csdn.net/bulo1025/article/details/88147425

题目描述

如果单词列表(words)中的一个单词包含牌照(licensePlate)中所有的字母,那么我们称之为完整词。在所有完整词中,最短的单词我们称之为最短完整词。

单词在匹配牌照中的字母时不区分大小写,比如牌照中的 “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” 且有着最短长度的完整词,但我们返回最先出现的完整词。

思路分析

  • letter列表记录licensePlate中小写字符
  • countle的value记录牌照中字符出现的个数
  • sortwords 是按长度排序后的words
  • 遍历sortwords,x 表示每个单词,用countx记录单词中字符出现的个数,用collection.Counter形成字典形式
  • 遍历countle,其记录车牌的字符出现次数,如果其中的key于countx中不对应,或者对应的key它的值大于单词中的值,那么就令flag为1
  • 最后,如果flag为0,说明该词就是最短完整词

代码示例

import collections
class Solution():
    def shortestCompletingWord(self, licensePlate, words):
        """
        :type licensePlate: str
        :type words: List[str]
        :rtype: str
        """
        letter = [i.lower() for i in licensePlate if  'a'<= i <='z' or 'A'<= i <= 'Z']
        countle = collections.Counter(letter)
        sortwords = sorted(words,key = len)
        for x in sortwords:
            flag = 0
            countx = collections.Counter(x)
            for key,val in countle.items():
                if key not in countx.keys() or  val > countx[key]:
                    flag = 1
                    break
            if flag == 0:
                return x

猜你喜欢

转载自blog.csdn.net/bulo1025/article/details/88147425
今日推荐