Given a dictionary, find all of the longest words in the dictionary.
Have you met this question in a real interview?
Yes
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) {
// write your code here
ArrayList<String> result = new ArrayList<String>();
int maxLen = 0;
for(String word : dictionary){
if(word.length() > maxLen){
result.clear();
result.add(word);
maxLen = word.length();
} else if(word.length() == maxLen){
result.add(word);
}
}
return result;
}
};
No comments:
Post a Comment