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

猜你喜欢

转载自www.cnblogs.com/yunxintryyoubest/p/12642388.html
今日推荐