Implement a trie with insertsearch, and startsWith methods.

Example:

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true

Note:

  • You may assume that all inputs are consist of lowercase letters a-z.
  • All inputs are guaranteed to be non-empty strings.

这道题让我们实现一个重要但又有些复杂的数据结构-字典树, 又称前缀树或单词查找树,详细介绍可以参见网友董的博客,例如,一个保存了8个键的trie结构,"A", "to", "tea", "ted", "ten", "i", "in", and "inn",如下图所示:

字典树主要有如下三点性质:

1. 根节点不包含字符,除根节点意外每个节点只包含一个字符。

2. 从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串。

3. 每个节点的所有子节点包含的字符串不相同。

字母树的插入(Insert)、删除( Delete)和查找(Find)都非常简单,用一个一重循环即可,即第i 次循环找到前i 个字母所对应的子树,然后进行相应的操作。实现这棵字母树,我们用最常见的数组保存(静态开辟内存)即可,当然也可以开动态的指针类型(动态开辟内存)。至于结点对儿子的指向,一般有三种方法:

1、对每个结点开一个字母集大小的数组,对应的下标是儿子所表示的字母,内容则是这个儿子对应在大数组上的位置,即标号;

2、对每个结点挂一个链表,按一定顺序记录每个儿子是谁;

3、使用左儿子右兄弟表示法记录这棵树。

三种方法,各有特点。第一种易实现,但实际的空间要求较大;第二种,较易实现,空间要求相对较小,但比较费时;第三种,空间要求最小,但相对费时且不易写。

我们这里只来实现第一种方法,这种方法实现起来简单直观,字母的字典树每个节点要定义一个大小为 26 的子节点指针数组,然后用一个标志符用来记录到当前位置为止是否为一个词,初始化的时候讲 26 个子节点都赋为空。那么 insert 操作只需要对于要插入的字符串的每一个字符算出其的位置,然后找是否存在这个子节点,若不存在则新建一个,然后再查找下一个。查找词和找前缀操作跟 insert 操作都很类似,不同点在于若不存在子节点,则返回 false。查找次最后还要看标识位,而找前缀直接返回 true 即可。代码如下:

class TrieNode {
public:
TrieNode *child[];
bool isWord;
TrieNode(): isWord(false) {
for (auto &a : child) a = nullptr;
}
}; class Trie {
public:
Trie() {
root = new TrieNode();
}
void insert(string s) {
TrieNode *p = root;
for (auto &a : s) {
int i = a - 'a';
if (!p->child[i]) p->child[i] = new TrieNode();
p = p->child[i];
}
p->isWord = true;
}
bool search(string key) {
TrieNode *p = root;
for (auto &a : key) {
int i = a - 'a';
if (!p->child[i]) return false;
p = p->child[i];
}
return p->isWord;
}
bool startsWith(string prefix) {
TrieNode *p = root;
for (auto &a : prefix) {
int i = a - 'a';
if (!p->child[i]) return false;
p = p->child[i];
}
return true;
} private:
TrieNode* root;
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/208

类似题目:

Add and Search Word - Data structure design

Design Search Autocomplete System

Replace Words

Implement Magic Dictionary

参考资料:

https://leetcode.com/problems/implement-trie-prefix-tree/

https://leetcode.com/problems/implement-trie-prefix-tree/discuss/58832/AC-JAVA-solution-simple-using-single-array

https://leetcode.com/problems/implement-trie-prefix-tree/discuss/58986/Concise-O(1)-JAVA-solution-based-on-HashMap

https://leetcode.com/problems/implement-trie-prefix-tree/discuss/58842/Maybe-the-code-is-not-too-much-by-using-%22next26%22-C%2B%2B

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 208. Implement Trie (Prefix Tree) 实现字典树(前缀树)的更多相关文章

  1. 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design

    字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...

  2. [LeetCode] 208. Implement Trie (Prefix Tree) ☆☆☆

    Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...

  3. LeetCode 208 Implement Trie (Prefix Tree) 字典树(前缀树)

    Implement a trie with insert, search, and startsWith methods.Note:You may assume that all inputs are ...

  4. Java for LeetCode 208 Implement Trie (Prefix Tree)

    Implement a trie with insert, search, and startsWith methods. Note: You may assume that all inputs a ...

  5. leetcode@ [208] Implement Trie (Prefix Tree)

    Trie 树模板 https://leetcode.com/problems/implement-trie-prefix-tree/ class TrieNode { public: char var ...

  6. 【LeetCode】208. Implement Trie (Prefix Tree)

    Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Note:You ...

  7. 【刷题-LeetCode】208. Implement Trie (Prefix Tree)

    Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Example: ...

  8. 【leetcode】208. Implement Trie (Prefix Tree 字典树)

    A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently s ...

  9. 【LeetCode】208. Implement Trie (Prefix Tree) 实现 Trie (前缀树)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,Trie, 前缀树,字典树,20 ...

随机推荐

  1. 机器学习(十一)-------- 异常检测(Anomaly Detection)

    异常检测(Anomaly Detection) 给定数据集

  2. Powershell ExecutionPolicy 执行策略

    简单说明 powershell对于脚本的执行有着严格的安全限制 Get-ExecutionPolicy -List #查看当前的执行策略 Set-ExecutionPolicy -Scope Curr ...

  3. [IDA] Oops! internal error 40343 occured.

    问题描述: 解决方案: 安装 IDA 时,其路径下不要出现中文.  

  4. 一款常用的截图工具(能够截gif动图)

    这款工具用来截程序的演示GIF图片,灰常方便. 直接上Github地址: https://github.com/NickeManarin/ScreenToGif

  5. easyui datagird 解决行高不一致问题!

    <style>.datagrid-btable .datagrid-cell {padding: 6px 4px;overflow: hidden;text-overflow: ellip ...

  6. Bacula Plugins

    1. loadPlugin 插件通过加载动态库loadPlugin函数开始,此函数包括bacula的回调和Plugin的注册 bacula的回调 typedef struct s_baculaFunc ...

  7. Scrum冲刺第一篇

    一.各个成员在 Alpha 阶段认领的任务 负责人和协作者 任务内容 陈嘉欣 设计编码规范 邓镇港 UI设计 肖烈涛 数据库设计 林德泽 设计测试计划 余晓东 用户注册登陆验证模块 陈嘉欣 余晓东 林 ...

  8. Python从零开始——模块与包

    一:Python模块知识概览 二:Python模块的定义与引入 三:模块的搜素与命名空间 四:深入模块 五:模块管理——包的定义与引入

  9. Linux内核调试的方式以及工具集锦【转】

    转自:https://blog.csdn.net/gatieme/article/details/68948080 版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原 ...

  10. docker研究-6 dockerfile 介绍使用

    Dockerfile是用来创建镜像的,首字母必须大写.