题目三十三:
给一个词典,找出其中所有最长的单词。
样例
在词典
{
"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
中, 最长的单词集合为 ["internationalization"]
在词典
{
"like",
"love",
"hate",
"yes"
}
中,最长的单词集合为 ["like", "love", "hate"]
挑战
遍历两次的办法很容易想到,如果只遍历一次你有没有什么好办法?
代码:
class Solution {
public:
/*
* @param dictionary: an array of strings
* @return: an arraylist of strings
*/
vector<string> longestWords(vector<string> &dictionary) {
// write your code here
vector<string> result;
int size = dictionary.size();
int max=0;
for(int i=0;i<size;i++)
{
if(dictionary[i].length()>max)
{
max=dictionary[i].length();
result.clear();
result.push_back(dictionary[i]);
}
else if(dictionary[i].length()==max)
result.push_back(dictionary[i]);
}
return result;
}
};
思路:出现单词长度大于max的单词时清空result,再重新填充。