lintcode :最长单词

题目:

给一个词典,找出其中所有最长的单词。

样例

在词典

{
  "dog",
  "google",
  "facebook",
  "internationalization",
  "blabla"
}

中, 最长的单词集合为 ["internationalization"]

在词典

{
  "like",
  "love",
  "hate",
  "yes"
}

中,最长的单词集合为 ["like", "love", "hate"]

挑战

遍历两次的办法很容易想到,如果只遍历一次你有没有什么好办法?

解题:

其实这个题目如果不是在这里做,我只能会暴力了,但是lintcode给你了需要返回的值,这个是很大的提示,这个题返回类型是ArrayList<String> ,然后就有思路了。值选取比较长的字符,加入list中,当碰到更长的时候可以清空list。

Java程序:

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.length==0)
            return result;
        int dictlen = dictionary[0].length();
        result.add(dictionary[0]);
        for( int i = 1;i<dictionary.length;i++){
            String tmp = dictionary[i];
            if( tmp.length()==dictlen){
                result.add( tmp );
            }else if(tmp.length()> dictlen){
                result.clear();
                result.add(tmp);
                dictlen = tmp.length();
            }
        }
        return result;
    }
};
View Code

总耗时: 1798 ms

Python程序:

class Solution:
    # @param dictionary: a list of strings
    # @return: a list of strings
    def longestWords(self, dictionary):
        # write your code here
        m = len( dictionary )
        result = []
        if m ==0:
            return result
        dictlen = len(dictionary[0])
        result.append(dictionary[0])
        for d in range(1,m):
            tmp = dictionary[d]
            if len(tmp) == dictlen:
                result.append(tmp)
            elif len(tmp)> dictlen:
                result = []
                dictlen = len(tmp)
                result.append(tmp)
        return result
View Code

总耗时: 405 ms

原文地址:https://www.cnblogs.com/theskulls/p/4887729.html