当前位置:网站首页>208. 实现 Trie (前缀树)
208. 实现 Trie (前缀树)
2022-07-01 03:23:00 【Sun_Sky_Sea】
208. 实现 Trie (前缀树)
原始题目链接:https://leetcode.cn/problems/implement-trie-prefix-tree/
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
提示:
1 <= word.length, prefix.length <= 2000
word 和 prefix 仅由小写英文字母组成
insert、search 和 startsWith 调用次数 总计 不超过 3 * 104 次
解题思路:
构建树的节点,使用字典存储子树结构,{word_char: 子树},标识从根节点到当前节点的路径,构成了一个关键词。
代码实现:
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word: str) -> None:
cur_node = self.root
for c in word:
cur_node = cur_node.children[c]
cur_node.flag = True
def search(self, word: str) -> bool:
cur_node = self.root
for c in word:
cur_node = cur_node.children.get(c)
if cur_node == None:
return False
return cur_node.flag
def startsWith(self, prefix: str) -> bool:
cur_node = self.root
for c in prefix:
cur_node = cur_node.children.get(c)
if cur_node == None:
return False
return True
# 定义一个节点
class Node(object):
def __init__(self):
# 使用字典存储子树结构,{word_char: 子树}
self.children = collections.defaultdict(Node)
# 标识从根节点到当前节点的路径,构成了一个关键词
self.flag = False
# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)
边栏推荐
- 报错:Plug-ins declaring extensions or extension points must set the singleton directive to true
- Avalanche problem and the use of sentinel
- 访问阿里云存储的图片URL实现在网页直接预览略缩图而不直接下载
- Addition without addition, subtraction, multiplication and division
- shell脚本使用两个横杠接收外部参数
- 复习专栏之---消息队列
- The shell script uses two bars to receive external parameters
- Promise中finally的用法
- Leetcode:829. Sum of continuous integers
- You cannot right-click F12 to view the source code solution on the web page
猜你喜欢

Ultimate dolls 2.0 | encapsulation of cloud native delivery

5、【WebGIS实战】软件操作篇——服务发布及权限管理

AfxMessageBox和MessageBox的用法

Leetcode 31 next spread, leetcode 64 minimum path sum, leetcode 62 different paths, leetcode 78 subset, leetcode 33 search rotation sort array (modify dichotomy)

The combination of applet container technology and IOT

家居网购项目

LeetCode 144二叉树的前序遍历、LeetCode 114二叉树展开为链表

Introduction to EtherCAT

深度学习中的随机种子torch.manual_seed(number)、torch.cuda.manual_seed(number)
![4. [WebGIS practice] software operation chapter - data import and processing](/img/5a/b86e0538660f27c809cf429053a06c.png)
4. [WebGIS practice] software operation chapter - data import and processing
随机推荐
Are you still wasting brain cells for self-study? This interview note is definitely the ceiling of station C
Ultimate dolls 2.0 | encapsulation of cloud native delivery
The preorder traversal of leetcode 144 binary tree and the expansion of leetcode 114 binary tree into a linked list
Develop industrial Internet with the technical advantages of small programs
Nacos
[深度学习]激活函数(Sigmoid等)、前向传播、反向传播和梯度优化;optimizer.zero_grad(), loss.backward(), optimizer.step()的作用及原理
pytorch训练深度学习网络设置cuda指定的GPU可见
Learning notes for introduction to C language multithreaded programming
不用加减乘除实现加法
复习专栏之---消息队列
go实现命令行的工具cli
AfxMessageBox和MessageBox的用法
Listener listener
10、Scanner. Next() cannot read spaces /indexof -1
后台系统右边内容如何出现滚动条和解决双滚动条的问题
Research on target recognition and tracking based on 3D laser point cloud
Leetcode:829. Sum of continuous integers
TEC: Knowledge Graph Embedding with Triple Context
访问阿里云存储的图片URL实现在网页直接预览略缩图而不直接下载
岭回归和lasso回归