720. 词典中最长的单词(any()和all()的用法)

any()是所有内容全是0,空,false才返回False。一旦有一个元素不是其中之一,就返回True。

all()是要求全部元素都不是0,空,false,一旦有一个元素是其中之一,就返回False。 

解答:https://blog.csdn.net/u010445301/article/details/81537343

解答一超过时间限制。

class Solution:
    def longestWord(self, words):
        """
        :type words: List[str]
        :rtype: str
        """
        res = [] #存放符合条件的单词()子单词都在
        if (len(words) == 0):
            return ''
        # list_words = sorted(words)
        # 暴力解法
        for word in words:
            new_word = word
            while new_word in words:
                new_word = new_word[:-1]
 
            if not new_word:
                res.append(word)
 
        #筛选出长度最长(序数最小的词)
        result = ''
        for key in res:
            if len(key)> len(result) or len(key) == len(result) and key < result:
                result = key
 
        return result
 
 
    def longestWord2(self, words):
 
        wordSet = set(words)
 
        result = ''
        for word in wordSet:
            if(len(word)>len(result) or len(word) == len(result) and word<result):
 
             if all(word[:k] in wordSet for k in range(1,len(word))) :
                 result = word
 
        return result
 
if __name__ == '__main__':
    words = ["w","wo","wor","worl", "world","worldss",'worlds']
    print(Solution().longestWord(words))

猜你喜欢

转载自blog.csdn.net/weixin_31866177/article/details/83052042