当前位置: 首页 > 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);
*/
http://www.lryc.cn/news/180936.html

相关文章:

  • 【Python】time模块和datetime模块的部分函数说明
  • Python 无废话-基础知识元组Tuple详讲
  • 【Win】Microsoft Spy++学习笔记
  • 如何解决版本不兼容Jar包冲突问题
  • 数据结构—归并排序-C语言实现
  • Multiple CORS header ‘Access-Control-Allow-Origin‘ not allowed
  • msvcp100.dll丢失怎样修复,msvcp100.dll丢失问题全面解析
  • 最新AI智能问答系统源码/AI绘画系统源码/支持GPT联网提问/Prompt应用+支持国内AI提问模型
  • 全连接网络实现回归【房价预测的数据】
  • mysql八股
  • MATLAB算法实战应用案例精讲-【优化算法】狐猴优化器(LO)(附MATLAB代码实现)
  • C#WPF动态资源和静态资源应用实例
  • 游戏逆向中的 NoClip 手段和安全应对方式
  • nodejs+vue流浪猫狗救助领养elementui
  • Css Flex 弹性布局中的换行与溢出处理方法
  • linux系统与应用
  • MySQL的结构化语言 DDL DML DQL DCL
  • P5488 差分与前缀和
  • uboot启动流程-uboot内存分配
  • LeetCode 面试题 08.02. 迷路的机器人
  • 画CMB天图使用Planck配色方案
  • 成都瀚网科技有限公司:抖店精选联盟怎么用?
  • 第二章:最新版零基础学习 PYTHON 教程(第五节 - Python 输入/输出–如何在Python中打印而不换行?)
  • C++实现集群聊天服务器
  • 40 二叉树的直径
  • Thread.sleep(0)的作用是什么?
  • 浏览器指定DNS
  • 虚拟机安装 centos
  • 【计算机网络笔记九】I/O 多路复用
  • 踩坑日记 《正确的使用Vuex》基于 uniapp Vue3 setup 语法糖 vuex4 项目 太多坑了要吐了