720. 詞典中最長的單詞(any()和all()的用法)
阿新 • • 發佈:2018-11-01
any()是所有內容全是0,空,false才返回False。一旦有一個元素不是其中之一,就返回True。
all()是要求全部元素都不是0,空,false,一旦有一個元素是其中之一,就返回False。
- python獲取最長單詞的方法:https://blog.csdn.net/cbbing/article/details/49814541
解答: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))