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

    1071. 词典中最长的单词

    中文English

    给出一系列字符串单词表示一个英语词典,找到字典中最长的单词,这些单词可以通过字典中的其他单词每次增加一个字母构成。 如果有多个可能的答案,则返回字典顺序最小的那个。

    如果没有答案,则返回空字符串。

    样例

    样例1:

    输入: 
    words = ["w","wo","wor","worl", "world"]
    输出: "world"
    解释: 
    单词"world" 可以通过 "w", "wo", "wor", and "worl"每次增加一个字母构成。
    

    样例2:

    输入: 
    words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
    输出: "apple"
    解释: 
    单词"apply" 和 "apple" 都能够通过字典里的其他单词构成。 但是 "apple" 的字典序比 “apply”小。
    

    注意事项

    1. 输入中的所有字符串只包含小写字母。
    2. words 的长度范围为 [1, 1000].
    3. words[i] 的长度范围为 [1, 30].
     
     
    输入测试数据 (每行一个参数)如何理解测试数据?
    class Solution:
        """
        @param words: a list of strings
        @return: the longest word in words that can be built one character at a time by other words in words
        """
        '''
        大致思路:
        1.给出一个方法,可以求当前要判断的单词是否符合条件,即在words里面是否存在切割单词
        2.初始化res,如果当前单词都存在切割单词在列表里面,返回True,则append到res里面,如果res里面存在多个的话,则需要判断大小即可,小的返回。
        '''
        def longestWord(self,words):
            max_l = 0
            return_word = ''
            res = []
            for word in words:
                if self.isExistSmallWord(word,words) == True:
                    if len(word) > max_l:
                        max_l = len(word)
                        ##在这里给定min_last初始值
                        min_last = word
    
                    res.append(word)
    
            
            #取出最大长度值相符的,然后根据多个相同最大值,进行判断最后一位大小,返回最小的
            for column in res:
                if len(column) == max_l:
                    ##在这里判断单词相同的中最小的一位即可
                    if column <= min_last:
                        min_last = column
                        return_word = column
            return return_word
                    
    
        def isExistSmallWord(self,word,words):
            #循环进行切割判断
            for i in range(1,len(word)):
                small_word = word[:i]
                if small_word not in words:
                    return False
            return True
  • 相关阅读:
    linux 用户、组,修改文件权限
    linux下获取帮助
    PHPSESSID的cookie//session_start()
    【python】import 模块、包、第三方模块
    python练习——最长的递减子序列
    python练习——水仙花数
    Linux目录结构
    Scala入门3(特质线性化)
    Scala入门2(特质与叠加在一起的特质)
    人工智能我见及特征提取mfcc算法理解
  • 原文地址:https://www.cnblogs.com/yunxintryyoubest/p/12642388.html
Copyright © 2011-2022 走看看