133. Longest Word
给一个词典,找出其中所有最长的单词。
样例
在词典
{
"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
中, 最长的单词集合为 ["internationalization"]
在词典
{
"like",
"love",
"hate",
"yes"
}
中,最长的单词集合为 ["like", "love", "hate"]
挑战
遍历两次的办法很容易想到,如果只遍历一次你有没有什么好办法?
利用哈希表,可以做到只遍历一次
#利用hash表来存储
def longestWords(self, dictionary):
# write your code here
hashmap = {}
max_key = 0
for item in dictionary:
if max_key < len(item):
max_key = len(item)
if len(item) not in hashmap:
hashmap[len(item)] = [item]
else:
hashmap[len(item)].append(item)
return hashmap[max_key]
两行代码解决
def longestWords(self, dictionary):
# write your code here
mlen = max(len(word) for word in dictionary)
return [word for word in dictionary if len(word) == mlen]