LeetCode //C - 208. Implement Trie (Prefix Tree)

208. Implement Trie (Prefix Tree)

A trie (pronounced as “try”) or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:

  • Trie() Initializes the trie object.
  • void insert(String word) Inserts the string word into the trie.
  • boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
  • boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.
     
Example 1:

Input:
[“Trie”, “insert”, “search”, “search”, “startsWith”, “insert”, “search”]
[[], [“apple”], [“apple”], [“app”], [“app”], [“app”], [“app”]]
Output:
[null, null, true, false, true, null, true]
Explanation:
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

Constraints:
  • 1 <= word.length, prefix.length <= 2000
  • word and prefix consist only of lowercase English letters.
  • At most 3 ∗ 1 0 4 3 * 10^4 3104 calls in total will be made to insert, search, and startsWith.

From: LeetCode
Link: 208. Implement Trie (Prefix Tree)


Solution:

Ideas:

1. TrieNode Structure:
Each node in the Trie is represented by a structure, TrieNode, which has the following components:

  • An array of pointers, children, where each pointer corresponds to a letter in the English alphabet.
  • A boolean flag, isEndOfWord, to signify whether a word ends at this node.

2. Trie Structure:
The Trie itself is represented by a structure, Trie, which holds a pointer to the root node of the Trie.

3. trieCreate:
This function initializes the Trie object and allocates memory for the root node of the Trie.

4. trieInsert:
This function inserts a word into the Trie. For each character in the word, it traverses down the Trie, creating new nodes if needed, until the end of the word is reached, at which point it sets the isEndOfWord flag to true.

5. trieSearch:
This function searches for a word in the Trie. It traverses down the Trie according to the characters in the word. If it reaches the end of the word and the isEndOfWord flag is true, the word exists in the Trie; otherwise, it doesn’t.

6. trieStartsWith:
This function checks whether there is any word in the Trie that starts with the given prefix. It traverses down the Trie according to the characters in the prefix. If it can traverse the entire prefix, then there exists a word in the Trie that starts with this prefix.

7. trieFree and freeNode:
These functions deallocate the memory used by the Trie and its nodes.

Code:
#define ALPHABET_SIZE 26typedef struct TrieNode {struct TrieNode *children[ALPHABET_SIZE];bool isEndOfWord;
} TrieNode;typedef struct {TrieNode *root;
} Trie;/** Initialize your data structure here. */
Trie* trieCreate() {Trie *trie = (Trie *)malloc(sizeof(Trie));trie->root = (TrieNode *)calloc(1, sizeof(TrieNode));return trie;
}/** Inserts a word into the trie. */
void trieInsert(Trie* obj, char * word) {TrieNode *node = obj->root;for (int i = 0; word[i] != '\0'; i++) {int index = word[i] - 'a';if (!node->children[index])node->children[index] = (TrieNode *)calloc(1, sizeof(TrieNode));node = node->children[index];}node->isEndOfWord = true;
}/** Returns if the word is in the trie. */
bool trieSearch(Trie* obj, char * word) {TrieNode *node = obj->root;for (int i = 0; word[i] != '\0'; i++) {int index = word[i] - 'a';if (!node->children[index])return false;node = node->children[index];}return node->isEndOfWord;
}/** Returns if there is any word in the trie that starts with the given prefix. */
bool trieStartsWith(Trie* obj, char * prefix) {TrieNode *node = obj->root;for (int i = 0; prefix[i] != '\0'; i++) {int index = prefix[i] - 'a';if (!node->children[index])return false;node = node->children[index];}return true;
}void freeNode(TrieNode *node) {for(int i = 0; i < ALPHABET_SIZE; i++)if(node->children[i])freeNode(node->children[i]);free(node);
}/** Deallocates the memory allocated for the Trie object. */
void trieFree(Trie* obj) {if(!obj) return;freeNode(obj->root);free(obj);
}/*** Your Trie struct will be instantiated and called as such:* Trie* obj = trieCreate();* trieInsert(obj, word);* bool param_2 = trieSearch(obj, word);* bool param_3 = trieStartsWith(obj, prefix);* trieFree(obj);
*/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.xdnf.cn/news/143768.html

如若内容造成侵权/违法违规/事实不符,请联系一条长河网进行投诉反馈,一经查实,立即删除!

相关文章

c++ 使用rapidjson对数据序列化和反序列化(vs2109)

RapidJSON是腾讯开源的一个高效的C JSON解析器及生成器&#xff0c;它是只有头文件的C库&#xff0c;综合性能是最好的。 1. 安装 在NuGet中为项目安装tencent.rapidjson 2. 引用头文件 #include <rapidjson/document.h> #include <rapidjson/memorystream.h> #…

java进阶-Netty

Netty 在此非常感谢尚硅谷学院以及韩顺平老师在B站公开课 Netty视频教程 Netty demo代码文件 I/O 说NIO之前先说一下BIO&#xff08;Blocking IO&#xff09;,如何理解这个Blocking呢&#xff1f;客户端监听&#xff08;Listen&#xff09;时&#xff0c;Accept是阻塞的&…

使用SPY++查看窗口信息去排查客户端UI软件问题

目录 1、使用SPY查看窗口的信息 2、使用SPY查看某些软件UI窗口用什么UI组件实现的 2.1、查看海康视频监控客户端安装包程序 2.2、查看华为协同办公软件WeLink 2.3、查看字节协同办公软件飞书 2.4、查看最新版本的Chrome浏览器 2.5、查看小鱼易连视频会议客户端软件 2.6…

WindTerm 安装使用教程【图解】

往期回顾 MobaXtermMobaXterm 安装使用教程【图解】-CSDN博客WindTermWindTerm 安装使用教程【图解】-CSDN博客 一、WindTerm 功能介绍 WindTerm 是一款 Github 上开源的 SSH 终端工具&#xff0c;到目前为止它已经收获了 16.9K 颗星&#xff0c;它是完全可以比肩 MobaXterm 工…

C语言的学习快速入门

可以按照以下步骤进行&#xff1a; 了解基本概念和语法&#xff1a;C语言是一种结构化的编程语言&#xff0c;了解基本的语法规则对于入门非常重要。可以学习关键字、变量、数据类型、运算符、控制结构等基本概念。学习编程环境&#xff1a;选择合适的编程环境&#xff0c;例如…

Spring事务几种的集中原因

Spring事务失效的几种原因 Spring Boot 项目中事务失效的原因可以有多种&#xff0c;这些原因可能导致你的事务无法正常工作。以下是一些常见的事务失效原因的详细讲解&#xff1a; 不使用Transactional注解&#xff1a; 事务需要通过Transactional注解来声明&#xff0c;如果…

基于yolov5的ignore classes训练

本文提到的忽略类别和检测中的忽略类别不一样&#xff0c;前者是在训练中加入忽略类&#xff0c;后者是在检测中仅检测想要的类。 ignore class的定义 我们在标注数据集的时候都是标注的正样本&#xff0c;训练过程中也是这样训练&#xff0c;让网络对正样本计算loss。但我们…

五、C#—字符串

&#x1f33b;&#x1f33b; 目录 一、字符串1.1 字符类型1.2 转义字符1.3 字符串的声明及赋值1.3.1 c# 中的字符串1.3.2 声明字符串1.3.3 使用字符串1.3.4 字符串的初始化1.3.4.1 引用字符串常量之初始化1.3.4.2 利用字符数组初始化1.3.4.3 提取数组中的一部分进行初始化 1.3.…

R的一些奇奇怪怪的功能

1. 欧氏距离计算 df <- data.frame(x 1:10, y 1:10, row.names paste0("s", 1:10)) euro_dist <- as.matrix(dist(df))2. 集合运算 union(x, y) # 并集 intersect(x, y) # 交集 setdiff(x, y) # 只在x中存在&#xff0c;y中不存在的元素 setequal(x, y)…

利用Redis实现全局唯一ID

利用Redis实现全局唯一ID 背景 场景分析&#xff1a;如果我们的id具有太明显的规则&#xff0c;用户或者说商业对手很容易猜测出来我们的一些敏感信息&#xff0c;比如商城在一天时间内&#xff0c;卖出了多少单&#xff0c;这明显不合适。 场景分析二&#xff1a;随着我们商…

慢性疼痛治疗服务公司Kindly MD申请700万美元纳斯达克IPO上市

来源&#xff1a;猛兽财经 作者&#xff1a;猛兽财经 猛兽财经获悉,慢性疼痛治疗服务公司Kindly MD近期已向美国证券交易委员会&#xff08;SEC&#xff09;提交招股书&#xff0c;申请在纳斯达克IPO上市&#xff0c;股票代码为&#xff08;KDLY&#xff09;,Kindly MD计划通过…

PTA程序辅助实验平台——2023年软件设计综合实践_3(分支与循环)

第一题&#xff1a;7-1 印第安男孩 - C/C 分支与循环 朵拉编程的时候也想顺便练习英语。她编程从键盘读入一个整数n&#xff0c;如果n值为0或者1&#xff0c;向屏幕输出“0 indian boy.”或“1 indian boy.”&#xff1b;如果n大于1&#xff0c;比如9&#xff0c;则输出“9 in…

计算机图像处理:图像轮廓

图像轮廓 图像阈值分割主要是针对图片的背景和前景进行分离&#xff0c;而图像轮廓也是图像中非常重要的一个特征信息&#xff0c;通过对图像轮廓的操作&#xff0c;就能获取目标图像的大小、位置、方向等信息。画出图像轮廓的基本思路是&#xff1a;先用阈值分割划分为两类图…

性能测试 —— 性能测试常见的测试指标 !

一、什么是性能测试 先看下百度百科对它的定义&#xff0c;性能测试是通过自动化的测试工具模拟多种正常、峰值以及异常负载条件来对系统的各项性能指标进行测试。 我们可以认为性能测试是&#xff1a;通过在测试环境下对系统或构件的性能进行探测&#xff0c;用以验证在生产环…

mysql面试题3:谈谈你知道的MySQL索引?MySQL中一个表可以创建多少个列索引?MySQL索引有哪几种?他们的优缺点是什么?

该文章专注于面试,面试只要回答关键点即可,不需要对框架有非常深入的回答,如果你想应付面试,是足够了,抓住关键点 面试官:谈谈你知道的MySQL索引? MySQL索引是一种特殊的数据结构,用于加速数据库的查询操作。它通过存储列值和对应记录的指针,可以快速定位到满足查询…

如果只是用php纯做api的话,给移动端做数据接口,是否需要用php框架?

API接口对接是现代软件开发中不可或缺的一部分&#xff0c;它允许不同的应用程序之间进行数据交换和服务调用。在PHP中&#xff0c;可以使用多种方式实现API接口的对接&#xff0c;包括基于HTTP协议的传统方法以及现代的API客户端库客户端库客户端库等。 一、实现API接口的对接…

【React】组件实例三大属性state、props、refs

state React 把组件看成是一个状态机&#xff08;State Machines&#xff09;。通过与用户的交互&#xff0c;实现不同状态&#xff0c;然后渲染 UI&#xff0c;让用户界面和数据保持一致。 React 里&#xff0c;只需更新组件的 state&#xff0c;然后根据新的 state 重新渲染用…

运行在浏览器中的Domino Designer开发客户机

大家好&#xff0c;才是真的好。 首先讨论一个非常有意思的事情&#xff0c;就是有人问&#xff0c;如果我用很老的Lotus软件&#xff0c;它是免费的吗&#xff1f; 这估计代表了很多盆友的心声。但不太友好的是&#xff0c;即使你用很老的Lotus软件&#xff08;例如Notes R4…

百度搜索逐步恢复优质网站权限

我是卢松松&#xff0c;点点上面的头像&#xff0c;欢迎关注我哦&#xff01; 从9月25日开始&#xff0c;有越来越多的站长和卢松松反馈&#xff0c;说他们的站可以正常入驻百度搜索资源平台了。我也试了试卢松松博客&#xff0c;果然&#xff0c;可以正常提交了。还是以前的…