给一个词典,找出其中所有最长的单词。
您在真实的面试中是否遇到过这个题?在词典
{
"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
中, 最长的单词集合为 ["internationalization"]
在词典
{
"like",
"love",
"hate",
"yes"
}
中,最长的单词集合为 ["like", "love", "hate"]
遍历两次的办法很容易想到,如果只遍历一次你有没有什么好办法?
相关题目 Expand
class Solution {
/**
* @param dictionary: an array of strings
* @return: an arraylist of strings
*/
ArrayList<String> longestWords(String[] dictionary) {
// write your code here
ArrayList<String> strList = new ArrayList<>();
int longest = 0;
for(int i=0;i<dictionary.length;i++){
int wordLen = dictionary[i].length();
if(wordLen>longest){
strList.clear();
strList.add(dictionary[i]);
longest = wordLen;
}else if(wordLen==longest){
strList.add(dictionary[i]);
}
}
return strList;
}
};