zoukankan      html  css  js  c++  java
  • 词典中最长的单词

    题目:

    首先要看懂题目。这个题目的意思就是你要找到一个单词,这个单词以第一个字母开头的连续子串都在这个单词数组中。并且如果有多个符合条件的单词那你就选择其中字典序最小的那一个。

    然后是思路。首先将单词数组按照字典序进行排序,然后从后向前,找到其中符合条件的单词。【这样做的目的是为了保证result数组中字典序大的单词排在前面】再对单词按照单词的长度进行排序。然后找到其中长度最大且字典序最小的单词。

    最后是代码:

    '''
        Given a str list,return the longest str in the list.And each substring which
        start with the beginning of the str can be found in the list.
        if there are several answers of the result,return the smallest str in lexicographical order
        @author: crystal
        @date:2018/6/22
    '''
    
    def longestword(words):
        length = len(words)
        if length == 0:
            return ""
        else:
            newwords = sorted(words)
            result = []
            for i in range(0, length):
                last_word = newwords[length-1-i]
                while last_word in newwords:
                    last_word = last_word[:-1]
                if not last_word:
                    result.append(newwords[length-1-i])
            if len(result) == 0:
                return ""
            result = sorted(result, key=lambda x: len(x), reverse=True)
            for i in range(0, len(result)):
                if i == (len(result) - 1) or len(result[i]) != len(result[i+1]):
                    return result[i]
            return ""
    
    if __name__ == "__main__":
        words = ["b","br","bre","brea","break","breakf","breakfa","breakfas","breakfast","l","lu","lun","lunc","lunch","d","di","din","dinn","dinne","dinner"]
        result = longestword(words)
        print(result)

    这道题是leetcode上的第720道题。这是地址:https://leetcode.com/problems/longest-word-in-dictionary/description/

    以下是我的代码的提交结果:

  • 相关阅读:
    Web 前端开发中一些兼容性问题及其解决办法 (持续更)
    沈逸的IT专栏---shenyisyn
    程序员该做的事
    职场需要切忌的几点——《程序员,你伤不起》
    百度天气API接口
    C#简单音乐播放器ListBox歌单列表
    CentOS7 安装java(jre 1.8)
    CentOS7 系统安装与设置
    这个可以有,记录下
    在centos 7中让网卡自启动
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/9205862.html
Copyright © 2011-2022 走看看