题目描述:给一个词典,找出其中所有最长的单词。
样例:在词典
{"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
中, 最长的单词集合为 ["internationalization"]
在词典
{
"like",
"love",
"hate",
"yes"
}
中,最长的单词集合为 ["like", "love", "hate"]
两次遍历的话太简单了,没什么可说的。所以我们尝试使用一次遍历。
思路是这样:用一个整型变量word_len来记录最长的单词的长度,一开始,当然就是第一个单词的长度;再用一个结果列表保存最长的单词,一开始,当然也就只有第一个单词一个,之后,开始扫描词典,若扫描到的单词长度和word_len的值一样,则将这个新单词加入结果列表,若比word_len大,则将word_len赋值为这个新单词的长度,同时清空结果列表,再将新单词加入结果列表;若新单词的长度比word_len小,什么都不做。
代码如下:
class Solution:
# @param dictionary: a list of strings
# @return: a list of strings
def longestWords(self, dictionary):
result = []
word_len = 0
for word in dictionary:
if len(word) > word_len:
word_len = len(word)
result = []
result.append(word)
elif len(word) == word_len:
result.append(word)
return result
# write your code here