lintcode-easy-Longest Words

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

 

posted @ 2016-02-26 07:41  哥布林工程师  阅读(203)  评论(0编辑  收藏  举报