Longest Words
Written on October 21, 2015
Tweet
Given a dictionary, find all of the longest words in the dictionary.
class Solution {
public ArrayList<String> longestWords(String[] dictionary) {
ArrayList<String> result = new ArrayList<String>();
if (dictionary == null) return result;
int maxLen = 0;
for (String str : dictionary) {
if (str.length() > maxLen) {
result.clear();
result.add(str);
maxLen = str.length();
} else if (str.length() == maxLen) {
result.add(str);
}
}
return result;
}
};