leetcode 720. Longest Word in Dictionary(python)

261 阅读1分钟

这是我参与更文挑战的第6天,活动详情查看: 更文挑战

描述

Given an array of strings words representing an English Dictionary, return the longest word in words that can be built one character at a time by other words in words.

If there is more than one possible answer, return the longest word with the smallest lexicographical order. If there is no answer, return the empty string.

Example 1:

Input: words = ["w","wo","wor","worl","world"]
Output: "world"
Explanation: The word "world" can be built one character at a time by "w", "wo", "wor", and "worl".	

Example 2:

Input: words = ["a","banana","app","appl","ap","apply","apple"]
Output: "apple"
Explanation: Both "apply" and "apple" can be built from other words in the dictionary. However, "apple" is lexicographically smaller than "apply".

Note:

1 <= words.length <= 1000
1 <= words[i].length <= 30
words[i] consists of lowercase English letters.

解析

根据题意,暴力解决,先在 words 中加入一个空字符串,然后对 words 进行字典排序。对每个 word 都进行判断,其所有的可能的前缀(包括空字符串)都在 words 中的单词,其会被加入 l ,然后找出 l 中最长的单词即为答案。

解答

class Solution(object):
    def longestWord(self, words):
        """
        :type words: List[str]
        :rtype: str
        """
        words+=['']
        words.sort()
        l=[]
        for word in words:
            for i in range(len(word)):
                tmp = word[:i]
                if tmp not in words:
                    break
            else:
                l.append(word)
        if len(l) == 0:
            return ''
        l.sort(key=lambda x:len(x), reverse=True)
        return l[0]
        	      
		

运行结果

Runtime: 780 ms, faster than 5.00% of Python online submissions for Longest Word in Dictionary.
Memory Usage: 14.1 MB, less than 30.77% of Python online submissions for Longest Word in Dictionary.

解析

看高手的解提思路,巧妙用了 set() ,判断每个单词的除去倒数第一个字母是否在 set 里,然后用一个变量保存最长的单词。

用判断新单词是否比最长单词更长的方式完成两个需求:1.找出最长;2.同样最长的情况下,保留字母序最小的。这样做的前提是先对 words 进行排序。

解答

class Solution(object):
    def longestWord(self, words):
        """
        :type words: List[str]
        :rtype: str
        """
        words.sort()
        s = set([''])
        r = ''
        for word in words:
            if word[:-1] in s:
                s.add(word)
                if len(word) > len(r):
                    r = word
        return r

运行结果

Runtime: 52 ms, faster than 93.85% of Python online submissions for Longest Word in Dictionary.
Memory Usage: 14.1 MB, less than 41.54% of Python online submissions for Longest Word in Dictionary.

原题链接:leetcode.com/problems/lo…

您的支持是我最大的动力