【简单】Lintcode 133:Longest Word

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;
    }
};


猜你喜欢

转载自blog.csdn.net/majichen95/article/details/80287233
今日推荐