标签:
Given a dictionary, find all of the longest words in the dictionary.
Given
{
"dog",
"google",
"facebook",
"internationalization",
"blabla"
}
the longest words are(is) ["internationalization"]
.
Given
{
"like",
"love",
"hate",
"yes"
}
the longest words are ["like", "love", "hate"]
.
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; } };
标签:
原文地址:http://www.cnblogs.com/goblinengineer/p/5219156.html