Given a dictionary, find all of the longest words in the dictionary.google
Givenspa
{ "dog", "google", "facebook", "internationalization", "blabla" }
the longest words are(is) ["internationalization"]
.code
Givenblog
{ "like", "love", "hate", "yes" }
the longest words are ["like", "love", "hate"]
.get
It's easy to solve it in two passes, can you do it in one pass?string
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>(); if(dictionary == null || dictionary.length == 0) return result; for(int i = 0; i < dictionary.length; i++){ if(result.size() == 0) result.add(dictionary[i]); else{ if(dictionary[i].length() > result.get(result.size() - 1).length()){ result = new ArrayList<String>(); result.add(dictionary[i]); } else if(dictionary[i].length() == result.get(result.size() - 1).length()){ result.add(dictionary[i]); } } } return result; } };