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. Linux 关闭防火墙命令

    用linux自己来访问web是可以的 比如 192.168.2.20就可以访问本机的相关页面 用192.168.2.20/phpmyadmin就可以访问数据库相关内容 可是,当别的局域网的电脑想访问时 ...

  2. embody the data item with the ability to control access to itself

    Computer Science An Overview _J. Glenn Brookshear _11th Edition Such communication needs have long b ...

  3. Delphi指针的用法

    DELPHI指针的使用 大家都认为,C语言之所以强大,以及其自由性,很大部分体现在其灵活的指针运用上.因此,说指针是C语言的灵魂,一点都不为过.同时,这种说法也让很多人产生误解,似乎只有C语言的指针才 ...

  4. Mysql操作笔记(持续更新)

    1.mysqldump备份导出 备份成sql mysqldump -hlocalIp -uuserName -p --opt --default-character-set=utf8 --hex-bl ...

  5. 【转】将 azw3 格式转换为 mobi 格式并保持原有排版格式

    小伙伴多次向 Kindle 伴侣提出一个问题,那就是通过 Calibre 将排版精美的 azw3 格式电子书转换成 mobi 格式后推送到 Kindle,排版格式会发生很大的变化,比如行距过窄.内嵌字 ...

  6. BLE-NRF51822教程-RSSI获取

    当手机和设备连接上后,设备端可以通过获取RSSI,在一定程度上判断手机离设备的相对距离的远近. 获取函数很简单直接调用sd_ble_gap_rssi_get 接口函数就行了,传入连接句柄和buff就能 ...

  7. 智能手机,医疗诊断,云会议(gotomeeting/citrix)

    在诊断领域已出现很多大有希望的创新,它们可能会起到真正的变革作用. 例如,有一种新技术可以让健康护理工作者用一部智能手机拍摄高质量的视网膜图像.这些数码照片像素很高,足以帮助检测白内障.黄斑退化.糖尿 ...

  8. LeetCode Search a 2D Matrix II

    原题链接在这里:https://leetcode.com/problems/search-a-2d-matrix-ii/ Write an efficient algorithm that searc ...

  9. WeUI—微信官方UI库

    WeUI 为微信 Web 服务量身设计 概述 WeUI是一套同微信原生视觉体验一致的基础样式库,由微信官方设计团队为微信 Web 开发量身设计,可以令用户的使用感知更加统一.包含button.cell ...

  10. JBoss远程方法调用漏洞利用详解

    早上起床打开微博看到空虚浪子心大神发的一篇有关Jboss漏洞的文章,对我等菜鸟来说那边文章看起来还是很吃力的,所以查了查国内外的资料,翻译写了这边文章,记录一下. 在JBoss服务器上部署web应用程 ...