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