Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

参考百度百科:Trie树

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的更多相关文章

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

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

  2. Leetcode208. Implement Trie (Prefix Tree)实现Trie(前缀树)

    实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个操作. 示例: Trie trie = new Trie(); trie.insert(" ...

  3. leetcode面试准备:Implement Trie (Prefix Tree)

    leetcode面试准备:Implement Trie (Prefix Tree) 1 题目 Implement a trie withinsert, search, and startsWith m ...

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

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

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

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

  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. 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  ...

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

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

随机推荐

  1. Universal Serial Bus USB 3.0

    Computer Systems A Programmer's Perspective Second Edition A Universal Serial Bus (USB) controller i ...

  2. 统计学习方法笔记 -- Boosting方法

    AdaBoost算法 基本思想是,对于一个复杂的问题,单独用一个分类算法判断比较困难,那么我们就用一组分类器来进行综合判断,得到结果,"三个臭皮匠顶一个诸葛亮" 专业的说法, 强可 ...

  3. html5之canvas初解

    <canvas> 元素本身并没有绘制能力(它仅仅是图形的容器) - 必须使用脚本来完成实际的绘图任务. getContext() 方法可返回一个对象,该对象提供了用于在画布上绘图的方法和属 ...

  4. yaf在windows7下32位的安装教程

    首先下载php_yaf.dll文件http://pecl.php.net/package/yaf/2.2.9/windows 打开扩展extension=php_yaf.dll 然后下载工具 http ...

  5. Qt配置信息设置(QSettings在不同平台下的使用路径)

    在Windows操作系统中,大多把配置文件信息写在注册表当中,或写在*.ini文件中,对于这两种操作都有相应的Windows API函数,在以前的文章中都提及过,这里就不多说了~ 在Qt中,提供了一个 ...

  6. 报javax.servlet.ServletException: Servlet.init() for servlet springmvc threw exception异常 的解决方案

    后台错误信息如下: javax.servlet.ServletException: Servlet.init() for servlet springmvc threw exception org.a ...

  7. Python 链接Mysql数据库

    参考链接:https://pypi.python.org/pypi/PyMySQL#downloads import pymysql.cursors,xml.dom.minidom # Connect ...

  8. 借用layer让弹层不限制在iframe内部

    使用方法: 1 除了layer的success,end,cancel回掉函数以外其它的layer参数都可以使用. 2 使用前在layer的js后边把该js引入(可以命名为layerExtend). 3 ...

  9. 实验一补充内容 Java开发环境的熟悉-刘蔚然

    本次实验 PSP时间统计 步骤 耗时百分比 需求分析 5% 设计 10% 代码实现 67% 测试 15% 分析总结 3%

  10. shell 使用for循环 启动后台任务

    为了统计多天的数据并按照天为文件名输出,写了脚本,脚本可以统计单天的数据.为了实现多天的同时进行采用 启动多个进程后台执行形式: 但是直接 执行的参数后面加上& 并不能解决,采用 echo & ...