当前位置: 首页 > news >正文

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);
*/

相关文章:

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 s…...

【Python】time模块和datetime模块的部分函数说明

时间戳与日期 在说到这俩模块之前&#xff0c;首先先明确几个概念&#xff1a; 时间戳是个很单纯的东西&#xff0c;没有“时区”一说&#xff0c;因为时间戳本质上是经过的时间。日常生活中接触到的“日期”、“某点某时某分”准确的说是时间点&#xff0c;都是有时区概念的…...

Python 无废话-基础知识元组Tuple详讲

“元组 Tuple”是一个有序、不可变的序列集合&#xff0c;元组的元素可以包含任意类型的数据&#xff0c;如整数、浮点数、字符串等&#xff0c;用()表示&#xff0c;如下示例&#xff1a; 元组特征 1) 元组中的各个元素&#xff0c;可以具有不相同的数据类型&#xff0c;如 T…...

【Win】Microsoft Spy++学习笔记

参考资料 《用VisualStudio\Spy查窗口句柄&#xff0c;监控窗口消息》 1. 安装 Spy是VS中的工具&#xff0c;所以直接安装VS就可以了&#xff1b; 2. 检查应用程序架构 ChatGPT-Bing: 对于窗口应用程序分析&#xff0c;确定应用程序是32位还是64位是很重要的&#xff0c;因…...

如何解决版本不兼容Jar包冲突问题

如何解决版本不兼容Jar包冲突问题 引言 “老婆”和“妈妈”同时掉进水里&#xff0c;先救谁&#xff1f; 常言道&#xff1a;编码五分钟&#xff0c;解冲突两小时。作为Java开发来说&#xff0c;第一眼见到ClassNotFoundException、 NoSuchMethodException这些异常来说&…...

数据结构—归并排序-C语言实现

引言&#xff1a;归并排序跟快速排序一样&#xff0c;都运用到了分治的算法&#xff0c;但是归并排序是一种稳定的算法&#xff0c;同时也具备高效&#xff0c;其时间复杂度为O(N*logN) 算法图解&#xff1a; 然后开始归并&#xff1a; 就是这个思想&#xff0c;拆成最小子问题…...

Multiple CORS header ‘Access-Control-Allow-Origin‘ not allowed

今天在修改天天生鲜超市项目的时候&#xff0c;因为使用了前后端分离模式&#xff0c;前端通过网关统一转发请求到后端服务&#xff0c;但是第一次使用就遇到了问题&#xff0c;比如跨域问题&#xff1a; 但是&#xff0c;其实网关里是有配置跨域的&#xff0c;只是忘了把前端项…...

msvcp100.dll丢失怎样修复,msvcp100.dll丢失问题全面解析

msvcp100.dll是一个动态链接库文件&#xff0c;属于 Microsoft Visual C Redistributable 的一个组件。它包含了 C 运行时库&#xff0c;这些库在运行程序时会被加载到内存中。msvcp100.dll文件的主要作用是为基于 Visual C 编写的程序提供必要的运行时支持。 当您运行一个基于…...

最新AI智能问答系统源码/AI绘画系统源码/支持GPT联网提问/Prompt应用+支持国内AI提问模型

一、AI创作系统 SparkAi创作系统是基于国外很火的ChatGPT进行开发的AI智能问答系统和AI绘画系统。本期针对源码系统整体测试下来非常完美&#xff0c;可以说SparkAi是目前国内一款的ChatGPT对接OpenAI软件系统。那么如何搭建部署AI创作ChatGPT&#xff1f;小编这里写一个详细图…...

全连接网络实现回归【房价预测的数据】

也是分为data&#xff0c;model&#xff0c;train&#xff0c;test import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optimclass FCNet(nn.Module):def __init__(self):super(FCNet,self).__init__()self.fc1 nn.Linear(331,200)s…...

mysql八股

1、请你说说mysql索引&#xff0c;以及它们的好处和坏处 检索效率、存储资源、索引 索引就像指向表行的指针&#xff0c;是一个允许查询操作快速确定哪些行符合WHERE子句中的条件&#xff0c;并检索到这些行的其他列值的数据结构索引主要有普通索引、唯一索引、主键索引、外键…...

MATLAB算法实战应用案例精讲-【优化算法】狐猴优化器(LO)(附MATLAB代码实现)

代码实现 MATLAB LO.m %======================================================================= % Lemurs Optimizer: A New Metaheuristic Algorithm % for Global Optimization (LO)% This work is published in Journal of "Applied …...

C#WPF动态资源和静态资源应用实例

本文实例演示C#WPF动态资源和静态资源应用 一、资源概述 静态资源(StaticResource)指的是在程序载入内存时对资源的一次性使用,之后就不再访问这个资源了。 动态资源(DynamicResource)指的是在程序运行过程中然会去访问资源。 WPF中,每个界面元素都含有一个名为Resources…...

游戏逆向中的 NoClip 手段和安全应对方式

文章目录 墙壁边界寻找碰撞 NoClip 是一种典型的黑客行为&#xff0c;允许你穿过墙壁&#xff0c;所以 NoClip 又可以认为是避免碰撞体积的行为 墙壁边界 游戏中设置了碰撞体作为墙壁边界&#xff0c;是 玩家对象 和墙壁发生了碰撞&#xff0c;而不是 相机 玩家对象有他的 X…...

nodejs+vue流浪猫狗救助领养elementui

第三章 系统分析 10 3.1需求分析 10 3.2可行性分析 10 3.2.1技术可行性&#xff1a;技术背景 10 3.2.2经济可行性 11 3.2.3操作可行性&#xff1a; 11 3.3性能分析 11 3.4系统操作流程 12 3.4.1管理员登录流程 12 3.4.2信息添加流程 12 3.4.3信息删除流程 13 第四章 系统设计与…...

Css Flex 弹性布局中的换行与溢出处理方法

Css Flex 弹性布局中的换行与溢出处理方法 CSS弹性布局&#xff08;Flex&#xff09;是CSS3中的一种新的布局方式&#xff0c;它能够帮助我们更加灵活地布局元素。在Flex弹性布局中&#xff0c;元素的布局仅依赖于父容器的设置&#xff0c;而不再需要复杂的相对或绝对定位。本…...

linux系统与应用

Windows中的硬盘和盘符的关系&#xff1b; 硬盘通常为一块到两块&#xff1b;数量与盘符没有直接关系&#xff1b;一块硬盘可以分为多个盘符&#xff0c;如c,d,e,f,g等&#xff1b;当然理论上也可以一块硬盘只有一个盘符&#xff1b;学习linux时&#xff0c;最好使用固态硬盘&a…...

MySQL的结构化语言 DDL DML DQL DCL

一、SQL结构化语言介绍 数据查询语言DQL&#xff1a;其语句称为“数据检索语言”&#xff0c;用以从库中获取数据&#xff0c;确定数据怎样在应用程序给出&#xff0c;保留select是dql&#xff08;也是所有sql&#xff09;用的最多的动词 数据操作语言DML:其语句包括动词insert…...

P5488 差分与前缀和

传送门:洛谷 前题提要:包含了简单的生成函数思想以及多项式乘法,是一道不可多得的多项式好题.故记录一下. 题意:给定一个长为 n 的序列 a&#xff0c;求出其 k 阶差分或前缀和。结果的每一项都需要对 1004535809取模。 对于差分和前缀和我们分开来讨论. 先讨论前缀和部分: …...

uboot启动流程-uboot内存分配

一. uboot启动流程 _main 函数中会调用 board_init_f 函数&#xff0c;本文继续简单分析一下 board_init_f 函数。 具体分析 board_init_f函数的第二部分&#xff1a;内存分配代码。 本文继上一篇文章的学习&#xff0c;地址如下&#xff1a; uboot启动流程-涉及board_init…...

深入解析 Git LFS 架构设计:Go 语言实现的大文件版本控制终极指南

深入解析 Git LFS 架构设计&#xff1a;Go 语言实现的大文件版本控制终极指南 【免费下载链接】git-lfs 项目地址: https://gitcode.com/gh_mirrors/git/git-lfs Git Large File Storage&#xff08;Git LFS&#xff09;是一个革命性的Git扩展&#xff0c;专为管理大型…...

ClawdBot详细步骤:从docker run到Dashboard访问的全流程解析

ClawdBot详细步骤&#xff1a;从docker run到Dashboard访问的全流程解析 1. 项目概述 ClawdBot是一个可以在本地设备上运行的个人AI助手&#xff0c;它使用vLLM提供后端模型能力&#xff0c;让你能够快速搭建一个功能强大的AI对话系统。这个项目最大的特点就是简单易用&#…...

基于MATLAB_SIMULINK_SIMSCAPE建模的用于组件尺寸的电动和混合动力飞机模型

基于MATLAB/SIMULINK/SIMSCAPE建模的用于组件尺寸的电动和混合动力飞机模型第一步&#xff1a;主脚本 (AircraftSizingMain.m) 在 MATLAB 中运行此脚本&#xff0c;它将定义参数并启动仿真。 matlab 编辑 1%% Aircraft Component Sizing Simulation Script 2% 适用于电动 (AE) …...

Phi-3-mini-128k-instruct实战:使用Qt开发跨平台AI桌面应用

Phi-3-mini-128k-instruct实战&#xff1a;使用Qt开发跨平台AI桌面应用 最近在捣鼓一些本地AI应用&#xff0c;发现很多开发者朋友对如何把大模型塞进自己的桌面程序里很感兴趣。特别是用C和Qt的&#xff0c;总觉得这块门槛有点高。其实没那么复杂&#xff0c;我今天就用微软开…...

RocketMQ客户端日志治理:从默认输出到Slf4j集成的实战配置

1. RocketMQ客户端日志的默认困境 第一次在Kubernetes集群里部署RocketMQ消费者服务时&#xff0c;我就被日志问题坑得不轻。早上刚到公司就收到告警&#xff0c;说某个Pod被驱逐了。查了半天才发现是日志文件把磁盘撑爆了——RocketMQ客户端默认把所有日志都输出到~/logs/rock…...

CTF选手必备:Fenjing全自动SSTI绕过WAF实战指南(附校队真题解析)

CTF选手必备&#xff1a;Fenjing全自动SSTI绕过WAF实战指南&#xff08;附校队真题解析&#xff09; 在CTF比赛中&#xff0c;SSTI&#xff08;服务器端模板注入&#xff09;漏洞一直是Web安全赛道的经典题型。随着WAF&#xff08;Web应用防火墙&#xff09;规则日益复杂&#…...

基于天问block的ASRPRO语音芯片进阶开发:串口调试、多线程优化与ADC采集实战

1. 串口调试实战&#xff1a;从基础配置到高级技巧 ASRPRO语音芯片内置的3组串口&#xff08;UART0/UART1/UART2&#xff09;是硬件调试的黄金通道。实测发现&#xff0c;UART0虽然默认用于程序烧录&#xff0c;但在开发阶段反而是最方便的调试接口——毕竟不需要额外接线&…...

Hunyuan-MT-7B在电子商务SEO中的应用:多语言关键词优化

Hunyuan-MT-7B在电子商务SEO中的应用&#xff1a;多语言关键词优化 1. 引言 想象一下&#xff0c;你经营着一家面向全球市场的电商网站&#xff0c;每天都有来自世界各地的用户访问。但很快你会发现一个问题&#xff1a;用中文写的产品描述&#xff0c;在英语、西班牙语或阿拉…...

5步掌握RuView:无需摄像头,用WiFi信号实现人体姿态追踪

5步掌握RuView&#xff1a;无需摄像头&#xff0c;用WiFi信号实现人体姿态追踪 【免费下载链接】RuView Production-ready implementation of InvisPose - a revolutionary WiFi-based dense human pose estimation system that enables real-time full-body tracking through …...

python微信小程序的AI健康问诊系统 个人健康评估系统

目录需求分析与功能设计技术架构设计核心功能实现评估算法开发数据安全与合规测试与部署迭代优化项目技术支持可定制开发之功能创新亮点源码获取详细视频演示 &#xff1a;文章底部获取博主联系方式&#xff01;同行可合作需求分析与功能设计 明确系统核心功能模块&#xff1a…...