Leetcode: Implement Trie (Prefix Tree) && Summary: Trie
Implement a trie with insert, search, and startsWith methods. Note:
You may assume that all inputs are consist of lowercase letters a-z.
参考百度百科:Trie树
a trie, also called digital tree and sometimes radix tree or prefix tree (as they can be searched by prefixes)
The time complexity to insert and to search is O(m), where m is the length of the string.
标准Trie树的应用和优缺点
(1) 全字匹配:确定待查字串是否与集合的一个单词完全匹配。如上代码fullMatch()。
(2) 前缀匹配:查找集合中与以s为前缀的所有串。
注意:Trie树的结构并不适合用来查找子串。这一点和前面提到的PAT Tree以及后面专门要提到的Suffix Tree的作用有很大不同。
优点: 查找效率比与集合中的每一个字符串做匹配的效率要高很多。在o(m)时间内搜索一个长度为m的字符串s是否在字典里。Predictable O(k) lookup time where k is the size of the key
缺点:标准Trie的空间利用率不高,可能存在大量结点中只有一个子结点,这样的结点绝对是一种浪费。正是这个原因,才迅速推动了下面所讲的压缩trie的开发。
什么时候用Trie?
It all depends on what problem you're trying to solve. If all you need to do is insertions and lookups, go with a hash table. If you need to solve more complex problems such as prefix-related queries, then a trie might be the better solution.
像word search II就是跟前缀有关,如果dfs发现当前形成的前缀都不在字典中,就没必要再搜索下去了,所以用trie不用hashSet
Easy version of implement Trie. TrieNode only contains TrieNode[] children, and boolean isWord two fields
class Trie {
class TrieNode {
TrieNode[] children;
boolean isWord;
public TrieNode() {
this.children = new TrieNode[26];
this.isWord = false;
}
} TrieNode root; /** Initialize your data structure here. */
public Trie() {
this.root = new TrieNode();
} /** Inserts a word into the trie. */
public void insert(String word) {
if (word == null || word.length() == 0) return;
TrieNode cur = this.root;
for (int i = 0; i < word.length(); i ++) {
if (cur.children[word.charAt(i) - 'a'] == null) {
cur.children[word.charAt(i) - 'a'] = new TrieNode();
}
cur = cur.children[word.charAt(i) - 'a'];
}
cur.isWord = true;
} /** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode cur = this.root;
for (int i = 0; i < word.length(); i ++) {
if (cur.children[word.charAt(i) - 'a'] == null) return false;
cur = cur.children[word.charAt(i) - 'a'];
}
return cur.isWord;
} /** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode cur = this.root;
for (int i = 0; i < prefix.length(); i ++) {
if (cur.children[prefix.charAt(i) - 'a'] == null) return false;
cur = cur.children[prefix.charAt(i) - 'a'];
}
return true;
}
}
Older version, TrieNode also has num and val fields, which might not be that useful.
class TrieNode {
// Initialize your data structure here.
int num; //How many words go through this TrieNode
TrieNode[] son; //collection of sons
boolean isEnd;
char val; public TrieNode() {
this.num = 0;
this.son = new TrieNode[26];
this.isEnd = false;
}
} 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;
char[] arr = word.toCharArray();
TrieNode node = this.root;
for (int i=0; i<arr.length; i++) {
int pos = (int)(arr[i] - 'a');
if (node.son[pos] == null) {
node.son[pos] = new TrieNode();
node.son[pos].num++;
node.son[pos].val = arr[i];
}
else {
node.son[pos].num++;
}
node = node.son[pos];
}
node.isEnd = true;
} // Returns if the word is in the trie.
public boolean search(String word) {
char[] arr = word.toCharArray();
TrieNode node = this.root;
for (int i=0; i<arr.length; i++) {
int pos = (int)(arr[i] - 'a');
if (node.son[pos] == null) return false;
node = node.son[pos];
}
return node.isEnd;
} // Returns if there is any word in the trie
// that starts with the given prefix.
public boolean startsWith(String prefix) {
char[] arr = prefix.toCharArray();
TrieNode node = this.root;
for (int i=0; i<arr.length; i++) {
int pos = (int)(arr[i] - 'a');
if (node.son[pos] == null) return false;
node = node.son[pos];
}
return true;
}
} // Your Trie object will be instantiated and called as such:
// Trie trie = new Trie();
// trie.insert("somestring");
// trie.search("key");
Leetcode: Implement Trie (Prefix Tree) && Summary: Trie的更多相关文章
- 【LeetCode】208. Implement Trie (Prefix Tree) 实现 Trie (前缀树)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 公众号:负雪明烛 本文关键词:Leetcode, 力扣,Trie, 前缀树,字典树,20 ...
- Leetcode208. Implement Trie (Prefix Tree)实现Trie(前缀树)
实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作. 示例: Trie trie = new Trie(); trie.insert(" ...
- leetcode面试准备:Implement Trie (Prefix Tree)
leetcode面试准备:Implement Trie (Prefix Tree) 1 题目 Implement a trie withinsert, search, and startsWith m ...
- [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) 、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 Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Example: ...
- LeetCode208 Implement Trie (Prefix Tree). LeetCode211 Add and Search Word - Data structure design
字典树(Trie树相关) 208. Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith ...
- 【leetcode】208. Implement Trie (Prefix Tree 字典树)
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently s ...
随机推荐
- smarty3.0中文手册文档API及使用指南
1.安装Smarty3.0一.什么是smarty?smarty是一个使用PHP写出来的模板PHP模板引擎,它提供了逻辑与外在内容的分离,简单的讲,目的就是要使用PHP程序员同美工分离,使用的程序员改变 ...
- MillWheel: Fault-Tolerant Stream Processing at Internet Scale
http://static.googleusercontent.com/media/research.google.com/zh-CN//pubs/archive/41378.pdf 为什么要做M ...
- poj1979
#include<stdio.h>int map[4][4]={'.','.','.','.', '#','.','.','.', '.','#','.','.', ...
- IOS 入门开发教程
object-c: http://mobile.51cto.com/iphone-261129.htm Objective-C入门教材 Objective-C入门教材 2011-05-11 15:58 ...
- this绑定
js中关于this的用法,在初期时候经常会弄混,即使现在,也不敢说就一定不会混,但是起码好很多了. 函数执行过程中,主要有4种方法决定this的绑定对象. 分别为:默认绑定.隐式绑定. 显示绑定和ne ...
- 借用layer让弹层不限制在iframe内部
使用方法: 1 除了layer的success,end,cancel回掉函数以外其它的layer参数都可以使用. 2 使用前在layer的js后边把该js引入(可以命名为layerExtend). 3 ...
- angularJS中controller的通信
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8&quo ...
- storyboard中xib文件不加载问题
今天在用Xcode6自定义视图控制器时附带了一个XIB文件,然后把自定义的类绑定到storyboard的ViewController,如图所示 , 发现RootViewController对应的xi ...
- git 初次使用
其实知道git很久了,也一度看了不少资料来学习指令.但是一直不明白到底我该咋办,我最疑惑的地方在于,本地代码是如何存储到远程服务器上的,那些指令在什么环境下执行,其实主要是目录问题.就是我在git s ...
- Jquery下拉效果
$('#触发元素').hover(function(){ $('#框框').slideDown(); //展开(动画效果)},function(){ $('#框框').slideUp(); //收起( ...