Given a dictionary, find all of the longest words in the dictionary.
Example
Given
{
"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
the longest words are(is) ["internationalization"].
Given
{
"like",
"love",
"hate",
"yes"
}
the longest words are ["like", "love", "hate"].
解题思路:
贪心算法。以字符的最长长度maxSize为贪心标记,初始化第一个元素为最长字符串,存入结果result数组中,遍历数组。
如果后面的元素长度与maxSize相等,则继续存入result数组;
如果后面元素长度大于maxSize时,说明前面的所有存进的变量皆小于这个长度,所以将result清空,重新修正maxSize,将新的元素存入result;
如果后面元素长度小于maxSize时,则不需做任何操作,继续遍历下一个元素。
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>::iterator it = dictionary.begin();//遍历指针
int maxSize = it->size();//最长字符的长度
vector<string> result;//存放结果
for(;it != dictionary.end();it++)
{
if(it->size() == maxSize)
result.push_back(*it);
else if(it->size() > maxSize)
{
maxSize = it->size();
result.clear();
result.push_back(*it);
}
}
return result;
}
};
本文介绍了一种使用贪心算法来找出字典中最长单词的方法。通过一次遍历即可高效地找到所有具有最大长度的单词,并将其返回。
1317

被折叠的 条评论
为什么被折叠?



