• 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

  • 相关阅读:
    【基础】Oracle 表空间和数据文件
    oracle学习笔记1:windows下oracle数据库安装及.net调用oracle数据库
    redis中文网站
    .NET中的消息队列
    .Net下的进程间的通讯 -- Windows消息队列
    1060 最复杂的数(反素数玄学dfs)
    1282 时钟(最小表示法+hash)
    1191 消灭兔子(贪心+优先队列)
    1366 贫富差距(floyed)
    1503 猪和回文(DP)
  • 原文地址:https://www.cnblogs.com/bbbblog/p/4887729.html
Copyright © 2020-2023  润新知