LeetCode 748 Shortest Completing Word 解题报告

题目要求

Find the minimum length word from a given dictionary words, which has all the letters from the string licensePlate. Such a word is said to complete the given string licensePlate

Here, for letters we ignore case. For example, "P" on the licensePlate still matches "p" on the word.

It is guaranteed an answer exists. If there are multiple answers, return the one that occurs first in the array.

The license plate might have the same letter occurring multiple times. For example, given a licensePlate of "PP", the word "pair" does not complete the licensePlate, but the word "supper" does.

题目分析及思路

给定一组字符串,要求找到符合要求的最短词。要求是该词必须含有所有来自字符串licensePlate中的字母,不区分大小写;且如果licensePlate中同一个字母出现了多次,则符合要求的词中的该字母也需要出现同样次数。保证一定至少存在一个结果,且如果有多个结果的话,则返回在字符串数组中第一次出现的那个结果。可以先获得licensePlate中所有的字母,且都转换成小写得到letters。之后遍历字符串数组中的每一个字符串中的每一个字母,去匹配letters中的字母。若该词符合要求且结果数组为空,则将该词放进结果数组;若数组不为空且该词的长度小于结果数组中词的长度,则用该词替换掉结果数组的词。最后返回结果数组中的第一个结果。

python代码 

class Solution:

    def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:

        letters = [c.lower() for c in licensePlate if c.isalpha()]

        res = []

        for word in words:

            for c in word:

扫描二维码关注公众号,回复: 5662299 查看本文章

                if c in letters:

                    letters.remove(c)

            if len(letters) == 0:

                if not res:

                    res.append(word)

                else:

                    if len(word) < len(res[-1]):

                        res.pop()

                        res.append(word)

            letters = [c.lower() for c in licensePlate if c.isalpha()]

        return res[0]

            

        

猜你喜欢

转载自www.cnblogs.com/yao1996/p/10598361.html