Given a dictionary, find all of the longest words in the dictionary.(do it in one pass)
简单题,直接写代码
class Solution {
/**
* @param dictionary: an array of strings
* @return: an arraylist of strings
*/
ArrayList<String> longestWords(String[] dictionary) {
ArrayList<String> res = new ArrayList<String>();
for(String str : dictionary) {
if(res.isEmpty() || str.length() == res.get(0).length()) {
res.add(str);
}
else if(res.isEmpty() || str.length() > res.get(0).length()) {
res.clear();
res.add(str);
}
}
return res;
}
};