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/

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

  • 相关阅读:
    JSP第四周作业
    JSP第二次作业
    软件测试1
    2021web课程设计
    面向对象程序综合设计课程设计-大富翁(个人博客)
    对于《提问回顾与个人总结》评论的回复
    难遇伯乐,幸得钟期——提问回顾与个人总结
    黄衫女子,黄衫好.png
    当遇到点炒饭的顾客——结对项目总结
    山鸣谷应,相得益彰——杰对项目-第二阶段总结
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/9205862.html
Copyright © 2011-2022 走看看