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/

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

  • 相关阅读:
    Redis_数据类型
    python 单独设置在plot每条线的label为中文
    制作9patch图片心得——Android开发使用类似QQ聊天的冒泡对话框
    Oracle数据库实验一建立数据库
    Postman使用总结
    jmeter使用小结
    python实现系统调用cmd命令的模块---subprocess模块
    程序进程线程之间的区别
    Fiddler抓包工具简介
    MySQL基础SQL命令---增删改查
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/9205862.html
Copyright © 2011-2022 走看看