[Lintcode Easy] Longest Words

Source: Internet
Author: User

Longest Words

Given A dictionary, find all of the longest words in the dictionary.

Example

Given

{  "dog",  "google",  "facebook",  "internationalization",  "blabla"}

The longest words is ["internationalization"] .

Given

{  "like",  "love",  "hate",  "yes"}

The longest words is ["like", "love", "hate"] .

Challenge

It's easy-to-solve it in the passes, can 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 for find out specific words.

Keep in mind how to initiate the int array.

classSolution {/**     * @paramDictionary:an Array of strings *@return: An ArrayList of strings*/ArrayList<String>longestwords (string[] dictionary) {//Write your code hereArrayList<String> newstring=NewArraylist<string>(); intcount[]=NULL; intm=dictionary.length; Count=New int[M]; intMax=0;  for(inti=0;i<dictionary.length;i++)        {            intn=dictionary[i].length (); Count[i]=N; Max=Math.max (N,max); }                 for(inti=0;i<dictionary.length;i++)        {            if(count[i]==max)            {Newstring.add (dictionary[i]); }        }                returnnewstring; }

If we use Hashtable, we can does it in one pass

Following is the code,

classSolution {/**     * @paramDictionary:an Array of strings *@return: An ArrayList of strings*/ArrayList<String>longestwords (string[] dictionary) {//Write your code hereHashMap<Integer,ArrayList<String>> map=NewHashmap<integer,arraylist<string>>(); intMax=0;  for(inti=0;i<dictionary.length;i++)        {           if(Map.containskey (Dictionary[i].length ())) {Map.get (Dictionary[i].length ()). Add (Dictionary[i]           ); }            Else{ArrayList<String> arr=NewArraylist<string>();               Arr.add (Dictionary[i]);           Map.put (Dictionary[i].length (), arr); } Max=Math.max (Dictionary[i].length (), Max); }        returnMap.get (max); }};

[Lintcode Easy] Longest Words

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.