当前位置:网站首页>208. implement trie (prefix tree)
208. implement trie (prefix tree)
2022-07-01 03:43:00 【Sun_ Sky_ Sea】
208. Realization Trie ( Prefix tree )
Original title link :https://leetcode.cn/problems/implement-trie-prefix-tree/
Trie( It sounds like “try”) Or say Prefix tree It's a tree data structure , Keys for efficient storage and retrieval of string datasets . This data structure has quite a number of application scenarios , For example, automatic completion and spelling check .
Please realize Trie class :
Trie() Initialize the prefix tree object .
void insert(String word) Insert a string into the forward tree word .
boolean search(String word) If the string word In the prefix tree , return true( namely , Has been inserted before retrieval ); otherwise , return false .
boolean startsWith(String prefix) If a string has been inserted before word One of the prefixes of is prefix , return true ; otherwise , return false .
Example :
Input
[“Trie”, “insert”, “search”, “search”, “startsWith”, “insert”, “search”]
[[], [“apple”], [“apple”], [“app”], [“app”], [“app”], [“app”]]
Output
[null, null, true, false, true, null, true]
explain
Trie trie = new Trie();
trie.insert(“apple”);
trie.search(“apple”); // return True
trie.search(“app”); // return False
trie.startsWith(“app”); // return True
trie.insert(“app”);
trie.search(“app”); // return True
Tips :
1 <= word.length, prefix.length <= 2000
word and prefix It's only made up of lowercase letters
insert、search and startsWith Call the number A total of No more than 3 * 104 Time
Their thinking :
Build the node of the tree , Use dictionary to store subtree structure ,{word_char: subtree }, Identify the path from the root node to the current node , Constitute a keyword .
Code implementation :
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
# Define a node
class Node(object):
def __init__(self):
# Use dictionary to store subtree structure ,{word_char: subtree }
self.children = collections.defaultdict(Node)
# Identify the path from the root node to the current node , Constitute a keyword
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)
边栏推荐
- [TA frost wolf \u may- hundred people plan] 2.4 traditional empirical lighting model
- Pathmeasure implements loading animation
- Server rendering technology JSP
- 10、Scanner. Next() cannot read spaces /indexof -1
- 30. 串联所有单词的子串
- 衡量两个向量相似度的方法:余弦相似度、pytorch 求余弦相似度:torch.nn.CosineSimilarity(dim=1, eps=1e-08)
- Gorilla/mux framework (RK boot): RPC error code design
- FCN全卷积网络理解及代码实现(来自pytorch官方实现)
- [TA frost wolf \u may - "hundred people plan"] 2.1 color space
- How to display scrollbars on the right side of the background system and how to solve the problem of double scrollbars
猜你喜欢

Appium fundamentals of automated testing - basic principles of appium

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

Pyramid Scene Parsing Network【PSPNet】论文阅读

Asgnet paper and code interpretation 2

FCN full Convolution Network Understanding and Code Implementation (from pytorch Official Implementation)

ASGNet论文和代码解读2

Valentine's Day is nothing.

Cookie&Session
![[deep learning] activation function (sigmoid, etc.), forward propagation, back propagation and gradient optimization; optimizer. zero_ grad(), loss. backward(), optimizer. Function and principle of st](/img/9f/187ca83be1b88630a6c6fbfb0620ed.png)
[deep learning] activation function (sigmoid, etc.), forward propagation, back propagation and gradient optimization; optimizer. zero_ grad(), loss. backward(), optimizer. Function and principle of st

4、【WebGIS实战】软件操作篇——数据导入及处理
随机推荐
392. 判断子序列
[小样本分割]论文解读Prior Guided Feature Enrichment Network for Few-Shot Segmentation
小程序容器技术与物联网IoT的结合点
Explain spark operation mode in detail (local+standalone+yarn)
bootsrap中的栅格系统
[深度学习]激活函数(Sigmoid等)、前向传播、反向传播和梯度优化;optimizer.zero_grad(), loss.backward(), optimizer.step()的作用及原理
pytorch nn. AdaptiveAvgPool2d(1)
Review column - message queue
Appium fundamentals of automated testing - basic principles of appium
完全背包问题
FCN full Convolution Network Understanding and Code Implementation (from pytorch Official Implementation)
214. 最短回文串
Ultimate dolls 2.0 | encapsulation of cloud native delivery
[TA frost wolf \u may- hundred people plan] 2.3 introduction to common functions
排序链表(归并排序)
Jeecgboot output log, how to use @slf4j
用小程序的技术优势发展产业互联网
RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs
Filter
[TA frost wolf \u may - "hundred people plan"] 2.1 color space