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"].
Challenge
It's easy to solve it in two passes, can you do it in one pass?
class Solution { /** * @param dictionary: an array of strings * @return: an arraylist of strings */ ArrayList<String> longestWords(String[] dictionary) { // write your code here ArrayList<String> result = new ArrayList<String>(); if(dictionary == null || dictionary.length == 0) return result; for(int i = 0; i < dictionary.length; i++){ if(result.size() == 0) result.add(dictionary[i]); else{ if(dictionary[i].length() > result.get(result.size() - 1).length()){ result = new ArrayList<String>(); result.add(dictionary[i]); } else if(dictionary[i].length() == result.get(result.size() - 1).length()){ result.add(dictionary[i]); } } } return result; } };
本文介绍了一种算法,该算法能从给定的字符串数组中找出所有最长的单词,并将其返回。通过一次遍历即可完成任务,提高了效率。

124

被折叠的 条评论
为什么被折叠?



