1.问题描述:
给一个词典,找出其中所有最长的单词。
2.样例:
在词典
{
"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
中, 最长的单词集合为 ["internationalization"]
在词典
{
"like",
"love",
"hate",
"yes"
}
中,最长的单词集合为 ["like", "love", "hate"]
3.代码:
遍历两次时,思路就是先第一次遍历字典,求得字典中最长的长度maxlength, 然后第二次遍历中把长度等于maxlength的字符串加入到结果集中。
class Solution:
"""
@param: dictionary: an array of strings
@return: an arraylist of strings
"""
def longestWords(self, dictionary):
# write your code here
length=len(dictionary)
maxlength=0
for i in range(length):
a=len(dictionary[i])
if a>maxlength:
maxlength=a
ans=[]
for i in range(length):
b=len(dictionary[i])
if b==maxlength:
ans.append(dictionary[i])
return ans
遍历一次时,在求maxlength的同时就准备好结果集,当maxlength发生变化时,先要清空ans[]。
class Solution:
"""
@param: dictionary: an array of strings
@return: an arraylist of strings
"""
def longestWords(self, dictionary):
# write your code here
length=len(dictionary)
maxlength=0
ans=[]
for i in range(length):
a=len(dictionary[i])
if a>maxlength:
maxlength=a
del ans[:]
ans.append(dictionary[i])
elif a==maxlength:
ans.append(dictionary[i])
return ans