码迷,mamicode.com
首页 > 其他好文 > 详细

lintcode-easy-Longest Words

时间:2016-02-26 08:06:48      阅读:172      评论:0      收藏:0      [点我收藏+]

标签:

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"].

Challenge

It‘s easy to solve it in two passes, can you do it in one pass?

 

class Solution {
    /**
     * @param dictionary: an array of strings
     * @return: an arraylist of strings
     */
    ArrayList<String> longestWords(String[] dictionary) {
        // write your code here
        ArrayList<String> result = new ArrayList<String>();
        
        if(dictionary == null || dictionary.length == 0)
            return result;
        
        for(int i = 0; i < dictionary.length; i++){
            if(result.size() == 0)
                result.add(dictionary[i]);
            else{
                if(dictionary[i].length() > result.get(result.size() - 1).length()){
                    result = new ArrayList<String>();
                    result.add(dictionary[i]);
                }
                else if(dictionary[i].length() == result.get(result.size() - 1).length()){
                    result.add(dictionary[i]);
                }
            }
        }
        
        return result;
    }
};

 

lintcode-easy-Longest Words

标签:

原文地址:http://www.cnblogs.com/goblinengineer/p/5219156.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!