题目
描述
给一个词典,找出其中所有最长的单词。
您在真实的面试中是否遇到过这个题?
样例
在词典
{
“dog”,
“google”,
“facebook”,
“internationalization”,
“blabla”
}
中, 最长的单词集合为 [“internationalization”]
在词典
{
“like”,
“love”,
“hate”,
“yes”
}
中,最长的单词集合为 [“like”, “love”, “hate”]
挑战
遍历两次的办法很容易想到,如果只遍历一次你有没有什么好办法?
解答
只需要遍历一次
public class LongestWord {
/*
* @param dictionary: an array of strings
* @return: an arraylist of strings
*/
public List<String> longestWords(String[] dictionary) {
// write your code here
int maxLength = 0;
Map<Integer, List<String>> countMap = new HashMap<Integer, List<String>>();
for (int i = 0; i < dictionary.length; i++) {
// 保存最大长度值
if (dictionary[i].length() > maxLength) {
maxLength = dictionary[i].length();
}
// 按照长度保存为list
if (countMap.get(dictionary[i].length()) == null) {
List countList = new ArrayList();
countList.add(dictionary[i]);
countMap.put(dictionary[i].length(), countList);
} else {
List countList = countMap.get(dictionary[i].length());
countList.add(dictionary[i]);
}
}
return countMap.get(maxLength);
}
}