208. Implement Trie (Prefix Tree)
题目:
Implement a trie with insert
, search
, and startsWith
methods.
链接: http://leetcode.com/problems/implement-trie-prefix-tree/
题解:
设计Trie。题目给了很多条件,所以大大简化了我们的思考时间。那么我们就构造一个经典的R-way Trie吧。首先要设计Trie节点,对R-way Trie的话我们使用一个R个元素的数组TrieNode[] next = new TrieNode[R],本题里R = 26,同时还有一个boolean变量isWord来确定当前节点是否为单词。 然后设计insert,search以及startWith。 具体设计思路完全参考了Sedgewick的课件,非常清楚。二刷要再多多练习计算复杂度以及Tenary-search Trie和Suffix Tree/Suffix Trie的东西,也要看一看Eric Demaine的MIT视频里String那一课。
Time Complexity - O(n) for each insert,search,startWith, Space Complexity - O(26n), n为word的平均长度。假如m个单词的话 Space Complexity是 - O(m * 26n)
class TrieNode {
// Initialize your data structure here.
public boolean isWord;
public TrieNode[] next;
private final int R = 26; // R-way Trie public TrieNode() {
next = new TrieNode[R];
}
} public class Trie {
private TrieNode root; public Trie() {
root = new TrieNode();
} // Inserts a word into the trie.
public void insert(String word) {
if(word == null || word.length() == 0)
return;
TrieNode node = root;
int d = 0; // depth/distance while(d < word.length()) {
char c = word.charAt(d);
if(node.next[c - 'a'] == null)
node.next[c - 'a'] = new TrieNode();
node = node.next[c - 'a'];
d++;
} node.isWord = true;
} // Returns if the word is in the trie.
public boolean search(String word) {
if(word == null || word.length() == 0)
return false;
TrieNode node = root;
int d = 0; while(d < word.length()) {
char c = word.charAt(d);
if(node.next[c - 'a'] == null) // did not find char within word
return false;
node = node.next[c - 'a'];
d++;
} return node.isWord;
} // Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
if(prefix == null || prefix.length() == 0)
return false;
TrieNode node = root;
int d = 0; while(d < prefix.length()) {
char c = prefix.charAt(d);
if(node.next[c - 'a'] == null) // did not find char within prefix
return false;
node = node.next[c - 'a'];
d++;
} return true;
}
} // Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
二刷:
还是写得少,并不熟悉,只有个大概印象,可能要刷三到四遍才会深刻一点。
对于TrieNode的设计:
- 一般的R-way Trie就是每一个节点TrieNode有R个子节点,我们可以用一个数组来表示子节点。
- 数组的大小要根据题意来定,比如这道题说明了alphabet = 'a' 到 'z', 那么我们的R就等于26,做一个26-way Trie就可以了。
- 要有一个boolean变量isWord来表明这个节点是否是单词的结尾。
- 在Trie里面的首先要初始化一个root节点。 TrieNode root = new TrieNode(); 这个节点我们不保存任何字母。
对于insert
- 首先处理一下边界条件
- 设置一个变量d = 0代表深度depth
- 设置一个TrieNode node = root,这里算是获取一个root的reference
- 当d < word.length()时,我们根据word.charAt(d) - 'a'来算得 word的第一个字母应该保存的位置index
- 查看word.next[index],假如其为空,那么我们要创建一个新的TrieNode。不为空的时候不用管,直接运行6。
- 更新node = node.next[index], d++, 继续处理word中的下一个字母
- 全部遍历完毕以后,设置node.isWord = true,表明root到这个node的路径是一个单词。
对于search和startWith
- 1 ~ 4步跟insert都一样
- 查看woird.next[index],假如其为空直接返回false
- 更新node = node.next[index], d++,继续查找word中的下一个字母
- 最后一步,对于Search来说,我们要根据node.isWord来决定是否查找成功。 对于startWith来说我们直接返回true。
Java:
Time Complexity - O(n) for each insert,search,startWith, Space Complexity - O(26n), n为word的平均长度。假如m个单词的话, Space Complexity就是是 - O(m * 26n)
class TrieNode {
// Initialize your data structure here.
TrieNode[] next;
boolean isWord;
int R = 26; // radix 'a' - 'z' public TrieNode() {
this.next = new TrieNode[R];
}
} public class Trie {
private TrieNode root; public Trie() {
root = new TrieNode();
} // Inserts a word into the trie.
public void insert(String word) {
if (word == null || word.length() == 0) return;
TrieNode node = root;
int d = 0;
while (d < word.length()) {
int index = word.charAt(d) - 'a';
if (node.next[index] == null) node.next[index] = new TrieNode();
node = node.next[index];
d++;
}
node.isWord = true;
} // Returns if the word is in the trie.
public boolean search(String word) {
if (word == null || word.length() == 0) return false;
TrieNode node = root;
int d = 0;
while (d < word.length()) {
int index = word.charAt(d) - 'a';
if (node.next[index] == null) return false;
node = node.next[index];
d++;
}
return node.isWord;
} // Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
if (prefix == null || prefix.length() == 0) return false;
TrieNode node = root;
int d = 0;
while (d < prefix.length()) {
int index = prefix.charAt(d) - 'a';
if (node.next[index] == null) return false;
node = node.next[index];
d++;
}
return true;
}
} // Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
Reference:
http://algs4.cs.princeton.edu/52trie/
https://en.wikipedia.org/wiki/Trie
https://en.wikipedia.org/wiki/Suffix_tree
208. Implement Trie (Prefix Tree)的更多相关文章
- 字典树(查找树) leetcode 208. Implement Trie (Prefix Tree) 、211. Add and Search Word - Data structure design
字典树(查找树) 26个分支作用:检测字符串是否在这个字典里面插入.查找 字典树与哈希表的对比:时间复杂度:以字符来看:O(N).O(N) 以字符串来看:O(1).O(1)空间复杂度:字典树远远小于哈 ...
- 【LeetCode】208. Implement Trie (Prefix Tree)
Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Note:You ...
- [LeetCode] 208. Implement Trie (Prefix Tree) ☆☆☆
Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...
- 【刷题-LeetCode】208. Implement Trie (Prefix Tree)
Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Example: ...
- 【LeetCode】208. Implement Trie (Prefix Tree) 实现 Trie (前缀树)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,Trie, 前缀树,字典树,20 ...
- 【leetcode】208. Implement Trie (Prefix Tree 字典树)
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently s ...
- [LeetCode] 208. Implement Trie (Prefix Tree) 实现字典树(前缀树)
Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie. ...
- 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 ...
- 208. Implement Trie (Prefix Tree) -- 键树
Implement a trie with insert, search, and startsWith methods. Note:You may assume that all inputs ar ...
随机推荐
- InnoDB 离线转储工具
一,应用场景; 1,表空间严重损坏,无法恢复;2,数据库表空间文件丢失后从磁盘上打捞出部分数据页面;3,恢复删除记录; 二,功能; 从数据页中直接转储出文本格式的行数据,从而可以后期用 LOAD DA ...
- POJ 2528 Mayor’s posters
Mayor's posters Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 37982 Accepted: 11030 ...
- DTcms 导航选中样式以及简化方法
(建议使用方法2,执行效率略高) 一般用于导航不能循环输出的情况. 可以循环输出导航的情况直接用if判断即可. 首页模版中顶部,自定义c#代码. <%set string channel=&qu ...
- css3选择器二
在HTML中,通过各种各样的属性可以给元素增加很多附加的信息,了解和掌握css3一些的选择器,是很有必要的. :enabled 和 :disabled选择器表单元素有可用(“:enabled”)和不可 ...
- PHP缓冲区强制及时输出
string '{"multicast_id":4917012850725514945,"success":0,"failure":38,& ...
- Android源代码编译——下载
下了好久的源代码,真真是慢哈.真希望国内有公司能够把镜像开放出来. 不多说,首先是系统环境,我的系统是Ubuntu 64位系统(14.04), 版本应该没什么. 需要的库 Git: 没话说必须, su ...
- php计算代码运行时间与内存使用的一段代码
计算运行时间及内存使用,代码如下: <?php //开始计时 $HeaderTime = microtime(true);//参数true表示返回浮点数值 //代码 //... printf(& ...
- Java单例模式--------懒汉式和饿汉式
单件模式用途:单件模式属于工厂模式的特例,只是它不需要输入参数并且始终返回同一对象的引用.单件模式能够保证某一类型对象在系统中的唯一性,即某类在系统中只有一个实例.它的用途十分广泛,打个比方,我们开发 ...
- IEtester不靠谱
对于刚刚学习前端的人来说,IEtester无疑是个测试神器, 刚开始用的时候,真有种如获至宝的兴奋. 然而,随着你学习的深入,你会慢慢地发现这个东西不太靠谱,而且会觉得没必要用它.为什么这么说呢? 首 ...
- 《WPF程序设计指南》读书笔记——第9章 路由输入事件
1.使用路由事件 路由事件是一种可以针对元素树中的多个侦听器(而不是仅针对引发该事件的对象)调用处理程序的事件.通俗地说,路由事件会在可视树(逻辑树是其子集)上,上下routed,如果哪个节点上订阅了 ...