[Lintcode easy]Longest Words

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,

using the word's length as key, words as value,

when it is the same key, add another words to hashmap.

find the max key, return its value.

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

 

转载于:https://www.cnblogs.com/kittyamin/p/4990422.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值