首页 > 其他 > 详细

[Lintcode easy]Longest Words

时间:2015-11-24 06:17:26      阅读:275      评论:0      收藏:0      [点我收藏+]

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?

 

////First,tracking the array to record every word‘s length, and find out the max length

////the second loop is to find out specific words.

/// keep in mind how to initiate the int array.

class Solution {
    /**
     * @param dictionary: an array of strings
     * @return: an arraylist of strings
     */
    ArrayList<String> longestWords(String[] dictionary) {
        // write your code here
   
        ArrayList<String> newString=new ArrayList<String>();
        
        int count[]=null;
        int m=dictionary.length;
        count=new int[m];
        int max=0;

        
        for(int i=0;i<dictionary.length;i++)
        {

            int n=dictionary[i].length();
            count[i]=n;
            max=Math.max(n,max);
        }
        
        for(int i=0;i<dictionary.length;i++)
        {
            if(count[i]==max)
            {
                newString.add(dictionary[i]);
            }
        }
        
        return newString;
       
    }

 

if we use hashtable, we can do it in one pass

following is the code,

class Solution {
    /**
     * @param dictionary: an array of strings
     * @return: an arraylist of strings
     */
    ArrayList<String> longestWords(String[] dictionary) {
        // write your code here

        HashMap<Integer,ArrayList<String>> map=new HashMap<Integer,ArrayList<String>>();
    
        int max=0;
        
        for(int i=0;i<dictionary.length;i++)
        {
           if(map.containsKey(dictionary[i].length()))
           {
                map.get(dictionary[i].length()).add(dictionary[i]);
           }
            else
           {
               ArrayList<String> arr=new ArrayList<String>();
               arr.add(dictionary[i]);
               map.put(dictionary[i].length(),arr);
           }
            max=Math.max(dictionary[i].length(),max);
        }
        return map.get(max);
    }
};

 

[Lintcode easy]Longest Words

原文:http://www.cnblogs.com/kittyamin/p/4990422.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!