• 748. 最短完整词


    如果单词列表(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" 且有着最短长度的完整词,但我们返回最先出现的完整词。
     

    注意:

    牌照(licensePlate)的长度在区域[1, 7]中。
    牌照(licensePlate)将会包含数字、空格、或者字母(大写和小写)。
    单词列表(words)长度在区间 [10, 1000] 中。
    每一个单词 words[i] 都是小写,并且长度在区间 [1, 15] 中。

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/shortest-completing-word

    class Solution:
        def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
            letters=[]
            for i in licensePlate:
                if i.isalpha():
                    letters.append(i.lower())
            def check(word):
                if len(word)>=len(letters):
                    flag=True
                    for i in set(letters):
                        if i not in word or letters.count(i)>word.count(i):
                            flag=False
                            break
                    return flag
            min_length=15
            macth=[]
            for word in words:
                if check(word):
                    min_length=min(min_length,len(word))
                    macth.append(word)
            for word in macth:
                if len(word)==min_length:
                    return word     
           

    优化==>

    class Solution:
        def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
            letters=[]
            for i in licensePlate:
                if i.isalpha():
                    letters.append(i.lower())
            words=sorted(words,key = lambda x:len(x))
            words=filter(lambda x:len(x)>=len(letters),words)
            for i in words:
                word=list(i)
                for j in letters:
                    if j in word:
                        word.remove(j)
                    else:
                        break
                else:
                    return i
  • 相关阅读:
    vue 兄弟组件间传值(bus方式)的坑(重复触发和首次未触发)
    vue 组件间传值(兄弟)(bus方式)
    vue 导出数据到excel
    vue-cli webpack打包后加载资源的路径问题
    vue组件传值之(父子)
    vue组件传值
    thinkphp 5 一些常见问题
    windows 安装 composer
    HTML H5响应式,表格,表单等
    面试
  • 原文地址:https://www.cnblogs.com/xxxsans/p/13564021.html
Copyright © 2020-2023  润新知