leetcode--720.词典中最长的单词

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

  • 示例:

# 示例 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" 
  • 提示:
    1 <= words.length <= 1000
    1 <= words[i].length <= 30
    所有输入的字符串 words[i] 都只包含小写字母。
  • 思路:

将数组words排序,按照单词的长度升序排序,长度相同则按照字典的降序排序
将答案初始化为空字符串,使用哈希集合存储所有符合要求的单词,初始化时将空字符串加入哈希集合。遍历数组words,对每个单词,判断当前字母去掉最后一个单词的前缀是否在哈希集合中,如果在则将当前单词加入哈希集合,并将答案更新为当前单词。遍历结束后,返回答案。

  • 解法一:
class Solution(object):
    def longestWord(self, words):
        """
        :type words: List[str]
        :rtype: str
        """
        words.sort(key=lambda x:(-len(x), x), reverse=True)
        longest = ""
        candidates = {""}
        for word in words:
            if word[:-1] in candidates:
                longest = word
                candidates.add(word)
        return longest

words.sort(key=lambda x:(-len(x), x), reverse=True)解释见链接: https://blog.csdn.net/weixin_46361294/article/details/123682488.

  • 解法二–字典树最小:

创建字典树,遍历数组 words 并将每个单词插入字典树。当所有的单词都插入字典树之后,将答案初始化为空字符串,再次遍历数组 words,判断每个单词是否是符合要求的单词,并更新答案。如果一个单词是符合要求的单词,则比较当前单词与答案,如果当前单词的长度大于答案的长度,或者当前单词的长度等于答案的长度且当前单词的字典序小于答案的字典序,则将答案更新为当前单词。

class Trie:
    def __init__(self):
        self.children = [None] * 26
        self.isEnd = False

    def insert(self, word: str):
        node = self
        for ch in word:
            ch = ord(ch) - ord('a')
            if not node.children[ch]:
                node.children[ch] = Trie()
            node = node.children[ch]
        node.isEnd = True

    def search(self, word: str):
        node = self
        for ch in word:
            ch = ord(ch) - ord('a')
            if node.children[ch] is None or not node.children[ch].isEnd:
                return False
            node = node.children[ch]
        return True

class Solution:
    def longestWord(self, words):
        t = Trie()
        for word in words:
            t.insert(word)
        longest = ""
        for word in words:
            if t.search(word) and (len(word) > len(longest) or len(word) == len(longest) and word < longest):
                longest = word
        return longest

words = ["a", "banana", "app", "appl", "ap", "apply", "apple"]
solution = Solution()
print(solution.longestWord(words))

  1. 来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/longest-word-in-dictionary ↩︎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值