lintcode-133-最长单词

133-最长单词

给一个词典,找出其中所有最长的单词。

样例

在词典
{
"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
中, 最长的单词集合为 ["internationalization"]
在词典
{
"like",
"love",
"hate",
"yes"
}
中,最长的单词集合为 ["like", "love", "hate"]

挑战

遍历两次的办法很容易想到,如果只遍历一次你有没有什么好办法?

标签

字符串处理 枚举法 LintCode 版权所有

思路

只遍历一次,默认最长单词为字典中第一个单词,记录其长度 maxLen ,若在之后的遍历中:

  • 若当前单词长度小于 maxLen ,继续遍历
  • 若当前单词长度等于 maxLen ,将此单词加入最长单词序列中
  • 若当前单词长度大于 maxLen ,更新 maxLen 为此单词长度,清除先前的最长单词序列,将此单词加入最长单词序列中

code

class Solution {
public:
    /**
     * @param dictionary: a vector of strings
     * @return: a vector of strings
     */
    vector<string> longestWords(vector<string> &dictionary) {
        // write your code here
        int size = dictionary.size(), maxLen = 0;
        if(size <= 0) {
            return vector<string>();
        }

        vector<string> result;
        maxLen = dictionary[0].size();
        result.push_back(dictionary[0]);
        for(int i=1; i<size; i++){
            if(maxLen < dictionary[i].size()) {
                maxLen = dictionary[i].size();
                result.clear();
                result.push_back(dictionary[i]);
            }
            else if(maxLen == dictionary[i].size()) {
                result.push_back(dictionary[i]);
            }
        }

        return result;
    }
};
posted @ 2017-07-21 18:29  LiBaoquan  阅读(448)  评论(0编辑  收藏  举报