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/

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

  • 相关阅读:
    关于自链接的视图的更新
    JavaScript局部变量与全局变量2
    减少IDE中的新建项
    whitespace对select无效
    学习摘录21
    让我记得写文档的设置
    本地连接不见了
    jquery 学习笔记
    jquery用load引入页面
    android笔记
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/9205862.html
Copyright © 2011-2022 走看看