Thursday, May 5, 2016

[LintCode] 133 Longest Words 解题报告

Description
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?


思路
过一遍。每检查一个元素,比较一下和结果里的长度是否有更新的必要。
如果比结果里的长度长,那么清空结果然后把这个元素加进去。 如果和结果里的长度相等,那么把它加入结果。


Code
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<>();
        
        for (int i = 0; i < dictionary.length; i++) {
            if (result.size() == 0) {
                result.add(dictionary[i]);
                continue;
            }
            if (result.get(0).length() < dictionary[i].length()) {
                result.clear();
                result.add(dictionary[i]);
            }
            else if (result.get(0).length() == dictionary[i].length()) {
                result.add(dictionary[i]);
            }
        }
        
        return result;
    }
}