lintcode-442-实现 Trie
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树的基本性质可以归纳为:
- 根节点不包含字符,除根节点意外每个节点只包含一个字符。
- 从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串。
- 每个节点的所有子节点包含的字符串不相同。
Trie树有一些特性:
- 根节点不包含字符,除根节点外每一个节点都只包含一个字符。
- 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
- 每个节点的所有子节点包含的字符都不相同。
- 如果字符的种数为n,则每个结点的出度为n,这也是空间换时间的体现,浪费了很多的空间。
- 插入查找的复杂度为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的更多相关文章
- [LintCode]——目录
Yet Another Source Code for LintCode Current Status : 232AC / 289ALL in Language C++, Up to date (20 ...
- Trie - 20181113
442. Implement Trie (Prefix Tree) class TrieNode { public boolean isWord; public TrieNode[] children ...
- [LintCode] Implement Trie 实现字典树
Implement a trie with insert, search, and startsWith methods. Have you met this question in a real i ...
- lintcode 中等题: Implement Trie
题目 Implement Trie Implement a trie with insert, search, and startsWith methods. 样例 注意 You may assu ...
- Implement Trie(LintCode)
Implement Trie Implement a trie with insert, search, and startsWith methods. 样例 注意 You may assume ...
- [leetcode/lintcode 题解] 微软 面试题:实现 Trie(前缀树)
实现一个 Trie,包含 insert, search, 和 startsWith 这三个方法. 在线评测地址:领扣题库官网 样例 1: 输入: insert(" ...
- Implement Trie (Prefix Tree) 解答
Question Implement a trie with insert, search, and startsWith methods. Note:You may assume that all ...
- leetcode & lintcode for bug-free
刷题备忘录,for bug-free leetcode 396. Rotate Function 题意: Given an array of integers A and let n to be it ...
- leetcode & lintcode 题解
刷题备忘录,for bug-free 招行面试题--求无序数组最长连续序列的长度,这里连续指的是值连续--间隔为1,并不是数值的位置连续 问题: 给出一个未排序的整数数组,找出最长的连续元素序列的长度 ...
随机推荐
- 撩妹技能 get,教你用 canvas 画一场流星雨
开始 妹子都喜欢流星,如果她说不喜欢,那她一定是一个假妹子. 现在就一起来做一场流星雨,用程序员的野路子浪漫一下. 要画一场流星雨,首先,自然我们要会画一颗流星. 玩过 canvas 的同学,你画圆画 ...
- PL/SQL轻量版(二)——基本语法
一.流程控制 1.条件判断 语法: IF <布尔表达式> THEN PL/SQL 和 SQL语句 END IF; IF <布尔表达式> THEN PL/SQL 和 SQL语句 ...
- Linux入门第五天——shell脚本入门(中)基础语法之判断与条件
一.判断式 利用 test 命令进行执行结果的判断(例如判断是否存在该文件):关于test test:test 示例:结合回传值 $? 进行判断:关于$?:$? [root@localhost tm ...
- !important用法:
如果不加important特性,则超链接的颜色为蓝色,但是加上important之后优先级提高了,显示颜色为绿色 <style type="text/css"> a{ ...
- 再论WPF中的UseLayoutRounding和SnapsToDevicePixels
原文:再论WPF中的UseLayoutRounding和SnapsToDevicePixels 版权声明:.net/web/医疗技术的木子纵横的个人分享 https://blog.csdn.net/m ...
- c++ 时间函数和结构化数据
time和localtime 数据结构概念 struct关键字 认识数据结构 自定义结构 例:获取当前系统日期和时间;(代码例子) 一.函数: time 函数time()返回的是当 ...
- pyqt5 菜单,工具栏,线程,matplotlib
import sys from PyQt5.QtGui import QIcon from PyQt5.QtWidgets import QMainWindow, QMenuBar, QToolBar ...
- 【JUC源码解析】ConcurrentHashMap
简介 支持并发的哈希表.其中包括红黑树,扩容,分槽计数等知识点. 源码分析 常量 private static final int MAXIMUM_CAPACITY = 1 << 30; ...
- runtime如何实现weak属性
首先了解weak是一种非拥有关系,属性所值对象销毁时,属性值会清空(nil). Runtime对注册的类会进行布局,对于weak对象会放入hash表中,用weak指向的内存地址作为key,当对象引用计 ...
- 用反射或委托优化switch太长的方法
在代码进行优化的时候,发现了switch case太长,有的竟然长达30个远远超过一屏这样在代码的可读性来说很差.特别在我们看代码的时候要拉下拉框我个人觉得这是不合理的.但是我不建议有switch就进 ...