【力扣日记】720 词典中最长的单词

题目描述

给出一个字符串数组words组成的一本英语词典。从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。

若无答案,则返回空字符串。

算法思路

根据题意新建字典,值属性为集合,可以更好的查询。

class Solution:
    def longestWord(self, words) -> str:
        d=dict(zip(range(1,31),[set()for i in range(31,61)]))
        words.sort(key=len)
        res=set()
        for i,j in enumerate(words):
            if len(j)==1:
                d[1].add(j)
                res.add(1)
            else:
                if j[:-1]in d[len(j)-1]:
                    d[len(j)].add(j)
                    res.add(len(j))
        return min(d[max(res)])

执行用时 :92 ms, 在所有 Python3 提交中击败了73.92%的用户
内存消耗 :13.9 MB, 在所有 Python3 提交中击败了7.14%的用户

发布了317 篇原创文章 · 获赞 44 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Heart_for_Ling/article/details/105407928