算法12-----词典中最长的单词

1、题目

给出一个字符串数组words组成的一本英语词典。从中找出最长的一个单词,该单词是由words词典中其他单词逐步添加一个字母组成。若其中有多个可行的答案,则返回答案中字典序最小的单词。

若无答案,则返回空字符串。

示例 1:

输入: 
words = ["w","wo","wor","worl", "world"]
输出: "world"
解释: 
单词"world"可由"w", "wo", "wor", 和 "worl"添加一个字母组成。

示例 2:

输入: 
words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
输出: "apple"
解释: 
"apply"和"apple"都能由词典中的单词组成。但是"apple"得字典序小于"apply"。

注意:

  • 所有输入的字符串都只包含小写字母。
  • words数组长度范围为[1,1000]
  • words[i]的长度范围为[1,30]

2、思路:

排序列表,从后往前遍历排序的列表,再遍历单词的子序列在不在列表中,若全在则把该单词加进结果列表中。最后找出结果列表中最长的单词,若多个单词长度一样,则选择字典序最前的。

代码1:

    def longestWord(self, words):
        """
        :type words: List[str]
        :rtype: str
        """
        res=[]
        if not words:
            return ""
        else:
            newWords=sorted(words)          
            for i in range(0,len(newWords)):
                last_word=newWords[len(newWords)-1-i]
                while last_word in newWords:
                    last_word=last_word[:-1]
                if not last_word:
                    res.append(newWords[len(newWords)-1-i])                
            result=sorted(res,key=lambda x:len(x),reverse=True)
            flag=0
            for i in range(0,len(result)):
                if i==len(result)-1 or len(result[i])!=len(result[i+1]):
                    flag=i
                    break
                else:
                    continue
        return "" if not result else result[i]

代码2:

    def longestWord(self, words):
    ans = ""
    wordset = set(words)
    for word in words:
        if len(word) > len(ans) or len(word) == len(ans) and word < ans:
            if all(word[:k] in wordset for k in range(1, len(word))):
                ans = word

    return ans

猜你喜欢

转载自www.cnblogs.com/Lee-yl/p/8971140.html