Topic:
the longest word
Give a dictionary and find out all the longest words in it.
Sample Example
In the dictionary
{ "dog", "google", "facebook", "internationalization", "blabla"}
, the longest word collection is["internationalization"]
In the dictionary
{ "like", "love", "hate", "yes"}
, the longest word collection is["like", "love", "hate"]
challenges
The way to traverse two times is very easy to think, if you only traverse once you have a good way?
Solving:
In fact, if this topic is not done here, I can only be violent, but lintcode give you need to return the value, this is a big hint, this question return type is arraylist<string>, and then there are ideas. The value selects a longer character, joins the list, and empties the list when it encounters a longer time.
Java Program:
classSolution {/** * @paramDictionary:an Array of strings *@return: An ArrayList of strings*/ArrayList<String>longestwords (string[] dictionary) {//Write your code herearraylist<string> result =NewArraylist<string>(); if(dictionary.length==0) returnresult; intDictlen = dictionary[0].length (); Result.add (dictionary[0]); for(inti = 1;i<dictionary.length;i++) {String tmp=Dictionary[i]; if(tmp.length () = =Dictlen) {Result.add (TMP); }Else if(Tmp.length () >Dictlen) {result.clear (); Result.add (TMP); Dictlen=tmp.length (); } } returnresult; }};
View Code
Total time: 1798 Ms
Python program:
classSolution:#@param dictionary:a List of strings #@return: A list of strings deflongestwords (Self, Dictionary):#Write your code herem =Len (dictionary) result= [] ifm = =0:returnresult Dictlen=Len (dictionary[0]) result.append (dictionary[0]) forDinchRange (1, M): TMP=Dictionary[d]ifLen (tmp) = =dictlen:result.append (TMP)elifLen (TMP) >Dictlen:result=[] Dictlen=Len (TMP) result.append (TMP)returnResult
View Code
Total time: 405 MS
Lintcode Easy title: Longest Words the longest word