题目:

Implement a trie with insertsearch, 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的设计:

  1. 一般的R-way Trie就是每一个节点TrieNode有R个子节点,我们可以用一个数组来表示子节点。
  2. 数组的大小要根据题意来定,比如这道题说明了alphabet = 'a' 到 'z', 那么我们的R就等于26,做一个26-way Trie就可以了。
  3. 要有一个boolean变量isWord来表明这个节点是否是单词的结尾。
  4. 在Trie里面的首先要初始化一个root节点。  TrieNode root = new TrieNode(); 这个节点我们不保存任何字母。

对于insert

  1. 首先处理一下边界条件
  2. 设置一个变量d = 0代表深度depth
  3. 设置一个TrieNode node = root,这里算是获取一个root的reference
  4. 当d < word.length()时,我们根据word.charAt(d) - 'a'来算得 word的第一个字母应该保存的位置index
  5. 查看word.next[index],假如其为空,那么我们要创建一个新的TrieNode。不为空的时候不用管,直接运行6。
  6. 更新node = node.next[index], d++, 继续处理word中的下一个字母
  7. 全部遍历完毕以后,设置node.isWord = true,表明root到这个node的路径是一个单词。

对于search和startWith

  1. 1 ~ 4步跟insert都一样
  2. 查看woird.next[index],假如其为空直接返回false
  3. 更新node = node.next[index], d++,继续查找word中的下一个字母
  4. 最后一步,对于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)的更多相关文章

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

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

  2. 【LeetCode】208. Implement Trie (Prefix Tree)

    Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Note:You ...

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

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

  4. 【刷题-LeetCode】208. Implement Trie (Prefix Tree)

    Implement Trie (Prefix Tree) Implement a trie with insert, search, and startsWith methods. Example: ...

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

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

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

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

  7. [LeetCode] 208. Implement Trie (Prefix Tree) 实现字典树(前缀树)

    Implement a trie with insert, search, and startsWith methods. Example: Trie trie = new Trie(); trie. ...

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

  9. 208. Implement Trie (Prefix Tree) -- 键树

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

随机推荐

  1. NTT研发

    2.研发标准 stead---大型机 css terasolunt---反向自动生成设计书 3.开发阶段做好设计,确定需求,测试阶段只是做产品有多差或者完成了多少需求,不是用来提高产品质量的过程

  2. JetBRAINS 系列注册机

    转载说明 本篇文章可能已经更新,最新文章请转:http://www.sollyu.com/1118/ 说明 这个是一国外的大牛写的一个 JetBRAINS 系列注册机,他里面包含了很多,我就不打字了. ...

  3. 结构型模式——Adapter

    1.意图 将一个类的接口转换成客户希望的另一个接口.使得原本由于接口不兼容而不能一起工作的那些类可以一起工作. 2.结构 类适配器 对象适配器 3.参与者 Target定义Client使用的与特定领域 ...

  4. NPOI Excel导入 导出

    添加引用 using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System; using System.Collections.Gene ...

  5. LESS学习总结

    之前在工作过程中,用到了Less,一直没有将学习心得整理归纳,今天终于空出时间整理了一下.   Less学习常用参考文档: Less 中文网 http://lesscss.cn/ 快速入门 | Les ...

  6. preventDefault()、stopPropagation()、return false 之间的区别

    “return false”之所以被误用的如此厉害,是因为它看起来像是完成了我们交给它的工作,浏览器不会再将我们重定向到href中的链接,表单也不会被继续提交,但这么做到底有什么不对呢? 可能在你刚开 ...

  7. jquery返回顶部特效

    <style> p#back-to-top{position:fixed; bottom:100px;right:10px; display: none; } p#back-to-top ...

  8. undefined local variable or method ‘xxx’ for #<RSpec::Core::ExampleGroup::Nested_1::Nested_1:0xbc88d6c>错误解决方案

    官方文档如下: https://github.com/rspec/rspec-rails/blob/master/Capybara.md Capybara 2.0 To use Capybara 2. ...

  9. PAT乙级真题1006. 换个格式输出整数 (15)(解题)

    原题: 让我们用字母B来表示“百”.字母S表示“十”,用“12...n”来表示个位数字n(<10),换个格式来输出任一个不超过3位的正整数.例如234应该被输出为BBSSS1234,因为它有2个 ...

  10. Oracle修改表空间大小

    在向orale数据库导入数据的时候报 ORA-01658: 无法为表空间 XXX中的段创建 INITIAL 区错误. Oracle我在创建表空间的时候初始化大小为200M,当数据库中数据量达到这个值, ...