引用塊內容
最長單詞
給一個詞典,找出其中所有最長的單詞。
在詞典
{
“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