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"]
.
分析:
因为要保持所有的最长string,所以我们可以用ARRAYLIST。如果arraylist为空,直接加进去,否则我们得把新的字符串和arraylist里面的字符串进行比较。如果小于arraylist里面的字符串,do nothing, 如果相等,则加进去,如果大于,则清空arraylist,然后把该字符串加进去。
1 class Solution { 2 /** 3 * @param dictionary: an array of strings 4 * @return: an arraylist of strings 5 */ 6 ArrayList<String> longestWords(String[] dictionary) { 7 if (dictionary == null || dictionary.length == 0) 8 return null; 9 ArrayList<String> list = new ArrayList<String>(); 10 11 for (String str : dictionary) { 12 if (list.size() == 0) { 13 list.add(str); 14 } else if (list.get(0).length() < str.length()) { 15 list.clear(); 16 list.add(str); 17 } else if (list.get(0).length() == str.length()) { 18 list.add(str); 19 } 20 } 21 return list; 22 } 23 }