LeetCode刷题日记2021-4-14/208. 实现 Trie (前缀树)

仅供自己学习记录

LeetCode刷题日记2021-4-14

题目描述

Trie(发音类似 “try”)或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有相当多的应用情景,例如自动补完和拼写检查。

请你实现 Trie 类:

  • Trie() 初始化前缀树对象。
  • void insert(String word) 向前缀树中插入字符串 word 。
  • boolean search(String word) 如果字符串 word 在前缀树中,返回true(即,在检索之前已经插入);否则,返回 false 。
  • boolean startsWith(String prefix) 如果之前已经插入的字符串 word 的前缀之一为 prefix ,返回true;否则,返回 false 。

示例:

输入

["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]

输出

[null, null, true, false, true, null, true]

解释

Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // 返回 True
trie.search("app");     // 返回 False
trie.startsWith("app"); // 返回 True
trie.insert("app");
trie.search("app");     // 返回 True

题解思路:

前缀树
(只保存小写字符的)「前缀树」是一种特殊的多叉树,它的 TrieNode 中 chidren 是一个大小为 26 的一维数组,分别对应了26个英文字符 ‘a’ ~ ‘z’,也就是说形成了一棵 26叉树。

前缀树的结构可以定义为下面这样。

里面存储了两个信息:

  • isWord 表示从根节点到当前节点为止,该路径是否形成了一个有效的字符串。

  • children 是该节点的所有子节点。

     class TrieNode {
     public:
         vector<TrieNode*> children;
         bool isWord;
         TrieNode() : isWord(false), children(26, nullptr) {
         }
         ~TrieNode() {
             for (auto& c : children)
                 delete c;
         }
     };
    

在构建前缀树的时候,按照下面的方法:

  • 根节点不保存任何信息;
  • 关键词放到「前缀树」时,需要把它拆成各个字符,每个字符按照其在 ‘a’ ~ ‘z’ 的序号,放在对应的 chidren里面。下一个字符是当前字符的子节点。
  • 一个输入字符串构建「前缀树」结束的时候,需要把该节点的 isWord 标记为 true,说明从根节点到当前节点的路径,构成了一个关键词。

下面是一棵「前缀树」,其中保存了 {“am”, “an”, “as”, “b”, “c”, “cv”} 这些关键词。图中红色表示 isWord 为 true。
看下面这个图的时候需要注意:

  • 所有以相同字符开头的字符串,会聚合到同一个子树上。比如 {“am”, “an”, “as”} ;
  • 并不一定是到达叶子节点才形成了一个关键词,只要 isWord 为true,那么从根节点到当前节点的路径就是关键词。比如 {“c”,“cv”} ;
    在这里插入图片描述

题解代码

定义前缀树节点类型
class Node(object):

	 def __int__(self):
		self.children=collections.default(Node)
		self.isWord=False


class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
		self.root=Node()

    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
		current=self.root
		for i in word:
			current=current.children[i]
		current.isWord=True

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        current=self.root
        for i in word:
        	current=current.children.get(i)
        	if current==None:
        		return False
		return current.isWord	

    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        current=self.root
        for i in prefix:
        	current=current.children.get(i)
        	if current is None:
        		return False
        return True

来源

https://leetcode-cn.com/problems/implement-trie-prefix-tree/solution/fu-xue-ming-zhu-cong-er-cha-shu-shuo-qi-628gs/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值