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?
class Solution {
/**
* @param dictionary: an array of strings
* @return: an arraylist of strings
*/
ArrayList<String> longestWords(String[] dictionary) {
if (dictionary == null || dictionary.length == 0) {
return new ArrayList<String>();
}
ArrayList<String> result = new ArrayList<String>();
int max = 0;
for (String s : dictionary) {
if (s.length() > max) {
result.clear();
max = s.length();
result.add(s);
} else if (s.length() == max) {
result.add(s);
}
}
return result;
}
}
Hope this helps,
Michael