问题描述:给一个词典,找出其中所有最长的单词。
样例:在词典
{
"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
中, 最长的单词集合为 ["internationalization"]
在词典
{
"like",
"love",
"hate",
"yes"
}
中,最长的单词集合为 ["like", "love", "hate"]
挑战:只遍历一次
class Solution {
public:
/**
* @param dictionary: a vector of strings
* @return: a vector of strings
*/
vector<string> longestWords(vector<string> &dictionary) {
// write your code here
vector<string> res;
if(dictionary.size()==0) return res;
int n=dictionary.size();
int LargetestLength=0;
for(int i=0;i<n;i++)
{
if(dictionary[i].size()==LargetestLength)
{
res.push_back(dictionary[i]);
}
else if(dictionary[i].size()>LargetestLength)
{
res.clear();
LargetestLength=dictionary[i].size();
res.push_back(dictionary[i]);
}
else continue;
}
return res;
}
};