0
点赞
收藏
分享

微信扫一扫

Leetcode刷题:字典树 类型题目总结

阎小妍 2022-03-17 阅读 87

词典中最长的单词

原文链接:
https://leetcode-cn.com/problems/longest-word-in-dictionary/

解题思路

涉及到前缀,便考虑使用字典树结构用于存储相同前缀的内容,当然本题也可以用hash表进行存储
遍历每个字符串,若前缀存在于字典树:

  • 存储最大的
  • 存储字典序最大的

实现代码


class Solution:
    def longestWord(self, words: List[str]) -> str:
        t = Trie() #不重复字典树的结构存储
        for word in words:t.insert(word) 
        longest = ""
        for word in words:
            if t.search(word):
                if(len(word) > len(longest) or (len(word) == len(longest) and word < longest)):
                    longest = word
        return longest

细节:
python字符串比较
逐位比较每一位字符的ASCII码的大小,无关字符串长度

’b’>‘aaaa’ 为True

举报

相关推荐

0 条评论