当前位置:网站首页>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)
边栏推荐
- 实现pow(x,n)函数
- Implement pow (x, n) function
- Force buckle - sum of two numbers
- 衡量两个向量相似度的方法:余弦相似度、pytorch 求余弦相似度:torch.nn.CosineSimilarity(dim=1, eps=1e-08)
- Processing of menu buttons on the left and contents on the right of the background system page, and double scrolling appears on the background system page
- [deep learning] activation function (sigmoid, etc.), forward propagation, back propagation and gradient optimization; optimizer. zero_ grad(), loss. backward(), optimizer. Function and principle of st
- [nine day training] content III of the problem solution of leetcode question brushing Report
- 【EI检索】2022年第六届材料工程与先进制造技术国际会议(MEAMT 2022)重要信息会议网址:www.meamt.org会议时间:2022年9月23-25日召开地点:中国南京截稿时间:2
- Ouc2021 autumn - Software Engineering - end of term (recall version)
- Research on target recognition and tracking based on 3D laser point cloud
猜你喜欢

C # realize solving the shortest path of unauthorized graph based on breadth first BFS -- complete program display

Jeecgboot output log, how to use @slf4j

pytorch训练深度学习网络设置cuda指定的GPU可见

快速筛选打卡时间日期等数据:EXCEL筛选查找某一时间点是否在某一时间段内

岭回归和lasso回归
![[small sample segmentation] interpretation of the paper: prior guided feature enrichment network for fee shot segmentation](/img/b3/887d3fb64acbf3702814d32e2e6414.png)
[small sample segmentation] interpretation of the paper: prior guided feature enrichment network for fee shot segmentation

Implement pow (x, n) function

How to display scrollbars on the right side of the background system and how to solve the problem of double scrollbars

数据交换 JSON
![5. [WebGIS practice] software operation - service release and permission management](/img/5d/070e207bd96e60ba1846d644d4fb54.png)
5. [WebGIS practice] software operation - service release and permission management
随机推荐
Thread data sharing and security -threadlocal
C # realize solving the shortest path of unauthorized graph based on breadth first BFS -- complete program display
10、Scanner.next() 无法读取空格/indexOf -1
[小样本分割]论文解读Prior Guided Feature Enrichment Network for Few-Shot Segmentation
Sort linked list (merge sort)
打包iso文件的话,怎样使用hybrid格式输出?isohybrid:command not found
Avalanche problem and the use of sentinel
Design of serial port receiving data scheme
后台系统右边内容如何出现滚动条和解决双滚动条的问题
数据库DDL(Data Definition Language,数据定义语言)知识点
Test function in pychram
bootsrap中的栅格系统
Overview of EtherCAT principle
多元线性回归
Keil5中如何做到 0 Error(s), 0 Warning(s).
Leetcode:剑指 Offer 59 - I. 滑动窗口的最大值
LeetCode 128最长连续序列(哈希set)
岭回归和lasso回归
Cookie&Session
BluePrism注册下载并安装-RPA第一章