引用块内容
最长单词
给一个词典,找出其中所有最长的单词。
在词典
{
“dog”,
“google”,
“facebook”,
“internationalization”,
“blabla”
}
中, 最长的单词集合为 [“internationalization”]在词典
{
“like”,
“love”,
“hate”,
“yes”
}
中,最长的单词集合为 [“like”, “love”, “hate”挑战
遍历两次的办法很容易想到,如果只遍历一次你有没有什么好办法?
只把最长的放在数组中就行了
class Solution:
# @param dictionary: a list of strings
# @return: a list of strings
def longestWords(self, dictionary):
# write your code here
a = list(dictionary)
b = []
temp = len(a[0])
for i in range(len(a)):
if len(a[i]) == temp:
b.append(a[i])
if len(a[i]) > temp:
temp = len(a[i])
b = [a[i]]
return b