• 词典中最长的单词


    题目:

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

    然后是思路。首先将单词数组按照字典序进行排序,然后从后向前,找到其中符合条件的单词。【这样做的目的是为了保证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/

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

  • 相关阅读:
    jvm内存分部
    vue 浏览器滚动行为
    vue中vueRouter使用
    vue脚手架的安装和使用
    vue 在路由中复用组件
    单例模式
    ser2net使用
    怎样使用万用表来测试板子上的TX和RX引脚
    STM32W芯片的JTAG口用于GPIO
    openwrt构建过程探索
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/9205862.html
Copyright © 2020-2023  润新知