442-实现 Trie

实现一个 Trie,包含 insert, search, 和 startsWith 这三个方法。

注意事项

你可以假设所有的输入都是小写字母a-z。

样例

insert("lintcode")

search("code") // return false

startsWith("lint") // return true

startsWith("linterror") // return false

insert("linterror")

search("lintcode) // return true

startsWith("linterror") // return true

标签

字典树 脸书 谷歌 优步

思路

字典树(Trie)可以保存一些 字符串->值 的对应关系。基本上,它跟 Java 的 HashMap 功能相同,都是 key-value 映射,只不过 Trie 的 key 只能是字符串。

Trie 的强大之处就在于它的时间复杂度。它的插入和查询时间复杂度都为 O(k) ,其中 k 为 key 的长度,与 Trie 中保存了多少个元素无关。Hash 表号称是 O(1) 的,但在计算 hash 的时候就肯定会是 O(k) ,而且还有碰撞之类的问题;Trie 的缺点是空间消耗很高。

Trie树的基本性质可以归纳为:

  1. 根节点不包含字符,除根节点意外每个节点只包含一个字符。
  2. 从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串。
  3. 每个节点的所有子节点包含的字符串不相同。

Trie树有一些特性:

  1. 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
  2. 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
  3. 每个节点的所有子节点包含的字符都不相同。
  4. 如果字符的种数为n,则每个结点的出度为n,这也是空间换时间的体现,浪费了很多的空间。
  5. 插入查找的复杂度为O(n),n为字符串长度。

基本思想(以字母树为例):

1、插入过程

对于一个单词,从根开始,沿着单词的各个字母所对应的树中的节点分支向下走,直到单词遍历完,将最后的节点标记为红色,表示该单词已插入Trie树。

2、查询过程

同样的,从根开始按照单词的字母顺序向下遍历trie树,一旦发现某个节点标记不存在或者单词遍历完成而最后的节点未标记为红色,则表示该单词不存在,若最后的节点标记为红色,表示该单词存在。

code

/**
* Your Trie object will be instantiated and called as such:
* Trie trie;
* trie.insert("lintcode");
* trie.search("lint"); will return false
* trie.startsWith("lint"); will return true
*/
class TrieNode {
public:
// Initialize your data structure here.
char c;
TrieNode * next[26];
bool isEnd; TrieNode() {
c = ' ';
for (int i = 0; i < 26; i++) {
next[i] = nullptr;
}
isEnd = false;
} TrieNode(char c) {
this->c = c;
for (int i = 0; i < 26; i++) {
next[i] = nullptr;
}
isEnd = false;
}
}; class Trie {
public:
Trie() {
root = new TrieNode();
} // Inserts a word into the trie.
void insert(string word) {
TrieNode* curNode = root;
for (int i = 0; i < word.size(); i++) {
if (curNode->next[word[i] - 'a'] != nullptr) {
curNode = curNode->next[word[i] - 'a'];
}
else {
TrieNode* node = new TrieNode(word[i]);
curNode->next[word[i] - 'a'] = node;
curNode = node;
}
}
curNode->isEnd = true;
} // Returns if the word is in the trie.
bool search(string word) {
TrieNode* curNode = root;
for (int i = 0; i < word.size(); i++) {
if (curNode->next[word[i] - 'a'] == nullptr) {
return false;
}
else {
curNode = curNode->next[word[i] - 'a'];
}
}
return curNode->isEnd;
} // Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode* curNode = root;
for (int i = 0; i < prefix.size(); i++) {
if (curNode->next[prefix[i] - 'a'] == nullptr) {
return false;
}
else {
curNode = curNode->next[prefix[i] - 'a'];
}
}
return true;
} private:
TrieNode* root;
};

lintcode-442-实现 Trie的更多相关文章

  1. [LintCode]——目录

    Yet Another Source Code for LintCode Current Status : 232AC / 289ALL in Language C++, Up to date (20 ...

  2. Trie - 20181113

    442. Implement Trie (Prefix Tree) class TrieNode { public boolean isWord; public TrieNode[] children ...

  3. [LintCode] Implement Trie 实现字典树

    Implement a trie with insert, search, and startsWith methods. Have you met this question in a real i ...

  4. lintcode 中等题: Implement Trie

    题目 Implement Trie Implement a trie with insert, search, and startsWith methods. 样例   注意 You may assu ...

  5. Implement Trie(LintCode)

    Implement Trie Implement a trie with insert, search, and startsWith methods. 样例   注意 You may assume ...

  6. [leetcode/lintcode 题解] 微软 面试题:实现 Trie(前缀树)

    实现一个 Trie,包含 ​insert​, ​search​, 和 ​startsWith​ 这三个方法.   在线评测地址:领扣题库官网     样例 1: 输入:    insert(" ...

  7. Implement Trie (Prefix Tree) 解答

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

  8. leetcode & lintcode for bug-free

    刷题备忘录,for bug-free leetcode 396. Rotate Function 题意: Given an array of integers A and let n to be it ...

  9. leetcode & lintcode 题解

    刷题备忘录,for bug-free 招行面试题--求无序数组最长连续序列的长度,这里连续指的是值连续--间隔为1,并不是数值的位置连续 问题: 给出一个未排序的整数数组,找出最长的连续元素序列的长度 ...

随机推荐

  1. HCNA(一)网络传输介质

    一 .同轴线缆 介绍:同轴线缆是一种早期的网络传输介质,同轴电缆的得名与它的结构相关,由内导体.外导体.绝缘介质和防护套四部分组成.同样支持10Mbps传输速率.现在已经基本被淘汰,不在应用于企业网络 ...

  2. Role Helper

    using System; using Microsoft.Xrm.Sdk; using Microsoft.Crm.Sdk.Messages; using System.Collections.Ge ...

  3. nRF52832 BLE_DFU空中升级OTA(三)准备升级工程(SDK14.2.0)

    准备需要加入DFU功能的工程 在工程main文件services_init函数中加入DFU服务 uint32_t err_code; // Initialize the async SVCI inte ...

  4. Vivado 调用自定义IP核

    关于Vivado如何创建自定义IP核有大量的参考文章,这里就不多加阐述了,本文目的主要是解决如何在新建工程中引用其它工程已经自定义封装好的IP核,从而实现自定义IP核的灵活复用. 举个例子,我们的目标 ...

  5. Linux入门进阶第三天——软件安装管理(下)

    一.yum在线安装 之前的rpm包各种依赖性太强!安装复杂,yum的好处就来了: // yum 在redhat是付费服务 1.yum源文件 先进入到yum目录: 我们打开默认生效的Base包 2.光盘 ...

  6. 柴柴随笔第三篇:安装虚拟机以及Linux基础入门

    虚拟机的安装 老师提供的作业指南给了我莫大的帮助,一步一步按着其中操作提示和网址链接,我首先下好了VM,也创建好了自己的第一台虚拟机. 接着按照步骤安装了Ubuntu到我的虚拟机. 到此,一切都顺风顺 ...

  7. 20155313 实验三《Java面向对象程序设计》实验报告

    一.实验内容 XP基础 XP核心实践 相关工具 二.实验要求 1.没有Linux基础的同学建议先学习<Linux基础入门(新版)><Vim编辑器>课程 2.完成实验.撰写实验报 ...

  8. 20155338 《Java程序设计》实验三(敏捷开发与XP实践)实验报告

    20155338 <Java程序设计>实验三(敏捷开发与XP实践)实验报告 一.实验内容及步骤 (一)使用Code菜单 • 在IDEA中使用工具(Code->Reformate Co ...

  9. MySQL入门篇(六)之mysqldump备份和恢复

    一.备份单个数据库 1.备份命令:mysqldump MySQL数据库自带的一个很好用的备份命令.是逻辑备份,导出 的是SQL语句.也就是把数据从MySQL库中以逻辑的SQL语句的形式直接输出或生成备 ...

  10. spark submit参数及调优(转载)

    spark submit参数介绍 你可以通过spark-submit --help或者spark-shell --help来查看这些参数. 使用格式:  ./bin/spark-submit \ -- ...