版权声明:本文为博主原创文章,未经博主允许不得转载。
难度:容易
要求:
给一个词典,找出其中所有最长的单词。
样例
给一个词典,找出其中所有最长的单词。
在词典{ "dog","google","facebook","internationalization","blabla"}中, 最长的单词集合为 ["internationalization"]
在词典{"like","love","hate","yes"}中,最长的单词集合为 ["like", "love", "hate"]
思路:
/**
* @param dictionary: an array of strings
* @return: an arraylist of strings
*/
public ArrayList<String> longestWords(String[] dictionary) {
if(dictionary == null){
return null;
}
ArrayList<String> result = new ArrayList<String>();
int max = 0;
for(int i = 0; i < dictionary.length; i++){
String dic = dictionary[i];
int len = dic.length();
if(len == max){
result.add(dic);
}else if(len > max){
max = len;
result.clear();
result.add(dic);
}
}
return result;
}