当前位置:网站首页>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)
边栏推荐
- 166. 分数到小数
- Leetcode:剑指 Offer 59 - I. 滑动窗口的最大值
- [深度学习]激活函数(Sigmoid等)、前向传播、反向传播和梯度优化;optimizer.zero_grad(), loss.backward(), optimizer.step()的作用及原理
- torch.histc
- Binary tree god level traversal: Morris traversal
- 【伸手党福利】开发人员重装系统顺序
- Nacos
- Valentine's Day is nothing.
- Split(), split(), slice(), can't you tell?
- Thread data sharing and security -threadlocal
猜你喜欢

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

The method to measure the similarity of two vectors: cosine similarity, pytorch calculate cosine similarity: torch nn. CosineSimilarity(dim=1, eps=1e-08)
![[nine day training] content III of the problem solution of leetcode question brushing Report](/img/7e/1e76181e56ef7feb083f9662df71c7.jpg)
[nine day training] content III of the problem solution of leetcode question brushing Report

二叉树神级遍历:Morris遍历

FCN全卷积网络理解及代码实现(来自pytorch官方实现)

后台系统右边内容如何出现滚动条和解决双滚动条的问题

Filter

数据库中COMMENT关键字的使用

【TA-霜狼_may-《百人計劃》】2.3 常用函數介紹
![5. [WebGIS practice] software operation - service release and permission management](/img/5d/070e207bd96e60ba1846d644d4fb54.png)
5. [WebGIS practice] software operation - service release and permission management
随机推荐
6. zigzag transformation
Unexpected token o in JSON at position 1 ,JSON解析问题
RSN:Learning to Exploit Long-term Relational Dependencies in Knowledge Graphs
数据库中COMMENT关键字的使用
5、【WebGIS实战】软件操作篇——服务发布及权限管理
Database DDL (data definition language) knowledge points
【EI会议】2022年第三届纳米材料与纳米技术国际会议(NanoMT 2022)
LeetCode 31下一个排列、LeetCode 64最小路径和、LeetCode 62不同路径、LeetCode 78子集、LeetCode 33搜索旋转排序数组(修改二分法)
Ouc2021 autumn - Software Engineering - end of term (recall version)
在 C 中声明函数之前调用函数会发生什么?
409. 最长回文串
Blueprism registration, download and install -rpa Chapter 1
Addition without addition, subtraction, multiplication and division
Avalanche problem and the use of sentinel
[TA frost wolf _may - "hundred people plan"] 1.4 introduction to PC mobile phone graphics API
Edlines: a real time line segment detector with a false detection control
Server rendering technology JSP
72. 编辑距离
Use of comment keyword in database
You cannot right-click F12 to view the source code solution on the web page