[LintCode] Longest Words

473 查看

Problem

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?
没有很理解challenge的意思,是说一个branch?

Solution

class Solution {
    ArrayList<String> longestWords(String[] dictionary) {
        // write your code here
        ArrayList<String> res = new ArrayList<String>();
        for (String word: dictionary) {
            if (res.isEmpty() || res.get(0).length() < word.length()) {
                res.clear();
                res.add(word);
            }
            else if (res.get(0).length() == word.length()) res.add(word);
            else continue;
        }
        return res;
    }
}