Implement a trie with insertsearch, and startsWith methods.

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

这道题让我们实现一个重要但又有些复杂的数据结构-字典树, 又称前缀树或单词查找树,详细介绍可以参见网友董的博客,例如,一个保存了8个键的trie结构,"A", "to", "tea", "ted", "ten", "i", "in", and "inn".如下图所示:

字典树主要有如下三点性质:

1. 根节点不包含字符,除根节点意外每个节点只包含一个字符。

2. 从根节点到某一个节点,路径上经过的字符连接起来,为该节点对应的字符串。

3. 每个节点的所有子节点包含的字符串不相同。

字母树的插入(Insert)、删除( Delete)和查找(Find)都非常简单,用一个一重循环即可,即第i 次循环找到前i 个字母所对应的子树,然后进行相应的操作。实现这棵字母树,我们用最常见的数组保存(静态开辟内存)即可,当然也可以开动态的指针类型(动态开辟内存)。至于结点对儿子的指向,一般有三种方法:

1、对每个结点开一个字母集大小的数组,对应的下标是儿子所表示的字母,内容则是这个儿子对应在大数组上的位置,即标号;

2、对每个结点挂一个链表,按一定顺序记录每个儿子是谁;

3、使用左儿子右兄弟表示法记录这棵树。

两种方法,各有特点。第一种易实现,但实际的空间要求较大;第二种,空间要求最小,但相对费时且不易写。

1.我们先来看第一种实现方法,这种方法实现起来简单直观,字母的字典树每个节点要定义一个大小为26的子节点指针数组,然后用一个标志符用来记录到当前位置为止是否为一个词,初始化的时候讲26个子节点都赋为空。那么insert操作只需要对于要插入的字符串的每一个字符算出其的位置,然后找是否存在这个子节点,若不存在则新建一个,然后再查找下一个。查找词和找前缀操作跟insert操作都很类似,不同点在于若不存在子节点,则返回false。查找次最后还要看标识位,而找前缀直接返回true即可

 1 class TrieNode {
 2     public char val;
 3     public boolean isWord;
 4     public TrieNode[] children = new TrieNode[26];
 5     public TrieNode() {}
 6     TrieNode(char c){
 7         TrieNode node = new TrieNode();
 8         node.val = c;
 9     }
10 }
11
12 public class Trie {
13     private TrieNode root;
14     public Trie() {
15         root = new TrieNode();
16         root.val = ' ';
17     }
18
19     public void insert(String word) {
20         TrieNode ws = root;
21         for(int i = 0; i < word.length(); i++){
22             char c = word.charAt(i);
23             if(ws.children[c - 'a'] == null){
24                 ws.children[c - 'a'] = new TrieNode(c);
25             }
26             ws = ws.children[c - 'a'];
27         }
28         ws.isWord = true;
29     }
30
31     public boolean search(String word) {
32         TrieNode ws = root;
33         for(int i = 0; i < word.length(); i++){
34             char c = word.charAt(i);
35             if(ws.children[c - 'a'] == null) return false;
36             ws = ws.children[c - 'a'];
37         }
38         return ws.isWord;
39     }
40
41     public boolean startsWith(String prefix) {
42         TrieNode ws = root;
43         for(int i = 0; i < prefix.length(); i++){
44             char c = prefix.charAt(i);
45             if(ws.children[c - 'a'] == null) return false;
46             ws = ws.children[c - 'a'];
47         }
48         return true;
49     }
50 }

2.

  1 class Trie {
  2     private String letter;
  3     private List<Trie> children;
  4     private boolean end;
  5     /** Initialize your data structure here. */
  6     public Trie() {
  7         this.letter = "";
  8         this.children = new ArrayList<Trie>();
  9         boolean end = false;
 10     }
 11
 12     public Trie(String letter) {
 13         this.letter = letter;
 14         this.children = new ArrayList<Trie>();
 15         this.end = false;
 16     }
 17
 18     /** Inserts a word into the trie. */
 19     public void insert(String word) {
 20         insertHelper(this, word, 0);
 21     }
 22
 23     /** Returns if the word is in the trie. */
 24     public boolean search(String word) {
 25         boolean result = true;
 26         result = result && searchHelper(this, word, 0);
 27         return result;
 28     }
 29
 30     /** Returns if there is any word in the trie that starts with the given prefix. */
 31     public boolean startsWith(String prefix) {
 32         if (prefix.length() == 0)
 33             return true;
 34         boolean result = false;
 35         for(Trie trie: children){
 36             if (trie.letter.equals(prefix.charAt(0) + "")){
 37                 result = true && startsWithHelper(trie, prefix, 1);
 38                 if(result == false)
 39                     return false;
 40             }
 41         }
 42         return result;
 43     }
 44
 45     private boolean startsWithHelper(Trie trie, String prefix, int pos){
 46         if(pos == prefix.length())
 47             return true;
 48         boolean result = false;
 49         for(Trie child: trie.children){
 50             if(child.letter.equals(prefix.charAt(pos) + "")){
 51                 result = true && startsWithHelper(child, prefix, pos +1);
 52                 if(result == false)
 53                     return false;
 54             }
 55         }
 56         return result;
 57     }
 58
 59     private void insertHelper(Trie trie, String word, int pos){
 60         boolean has = false;
 61         if(pos == word.length())
 62             return;
 63         int len = trie.children.size();
 64         for(int i=0; i < len; i++){
 65             Trie child = trie.children.get(i);
 66             if(child.letter.equals(word.charAt(pos) + "")){
 67                 has = true;
 68                 if(pos == word.length()-1){
 69                     if(child.end == false){
 70                         child.end = true;
 71                     }
 72                 }
 73                 insertHelper(child, word, pos+1);
 74             }
 75         }
 76         if(!has)
 77             create(trie,word,pos);
 78     }
 79
 80     private void create(Trie parent, String word, int pos){
 81         if(pos == word.length())
 82             return;
 83         Trie child = new Trie(word.charAt(pos) + "");
 84         if(pos == word.length() -1)
 85             child.end = true;
 86         parent.children.add(child);
 87         create(child, word, pos+1);
 88     }
 89
 90     private boolean searchHelper(Trie trie, String word, int pos){
 91         if(pos == word.length() && trie.children.size() == 0)
 92             return true;
 93         else if(pos == word.length())
 94             return false;
 95         boolean result = false;
 96         for(Trie child: trie.children){
 97             if(child.letter.equals(word.charAt(pos) + "")){
 98                 if(pos == word.length() -1){
 99                     if(child.end == true)
100                         return true;
101                     else
102                         return false;
103                 }
104                 result = true && searchHelper(child, word, pos +1);
105                 if(result == false)
106                     return false;
107             }
109         }
110         return result;
111     }
112 }

转载于:https://www.cnblogs.com/hanhanhan93/p/7534528.html

LeetCode 208. Implement Trie (Prefix Tree)相关推荐

  1. leetcode 208. Implement Trie (Prefix Tree) | 208. 实现 Trie 前缀树(Java)

    题目 https://leetcode.com/problems/implement-trie-prefix-tree/ 题解 第一版:暴力法 import java.util.LinkedHashS ...

  2. 208. Implement Trie (Prefix Tree)(Leetcode每日一题-2021.04.14)

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

  3. 208. Implement Trie (Prefix Tree)

    题目: Implement a trie with insert, search, and startsWith methods. 链接: http://leetcode.com/problems/i ...

  4. [LeetCode]Implement Trie (Prefix Tree)

    题目:Implement Trie (Prefix Tree) 实现字典树. 什么是字典树? Trie树,又叫字典树.前缀树(Prefix Tree).单词查找树 或 键树,是一种多叉树结构.如下图: ...

  5. Leetcode 208.实现 Trie (前缀树)(Implement Trie (Prefix Tree))

    Leetcode 208.实现 Trie (前缀树) 1 题目描述(Leetcode题目链接)   实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三 ...

  6. LeetCode Implement Trie (Prefix Tree)(字典树)

    问题:实现具有insert,search,startsWith方法的字典树 思路:就是要实现Trie数据结构 具体代码参考: https://github.com/wuli2496/OJ/tree/m ...

  7. LeetCode Implement Trie(Prefix Tree)

    131231231 转载于:https://www.cnblogs.com/ZHONGZHENHUA/p/10905337.html

  8. LeetCode-208 Implement Trie (Prefix Tree)

    题目描述 Implement a trie with insert, search, and startsWith methods. 题目大意 实现对一棵树的插入.搜索以及前序查找操作. (树的每个节 ...

  9. LeetCode 208. 实现 Trie (前缀树) —— 提供一套前缀树模板

    208. 实现 Trie (前缀树) Ideas 前缀树嘛,直接套模板咯,把之前写的拿过来抄一遍. 提供一下我的模板. Code Python class TrieNode:def __init__( ...

最新文章

  1. HDU Problem 1272 小希的迷宫 【并查集】
  2. Mapreduce基本工作流程
  3. 根据控件句柄读控件在内存的数据_WPF 2020界面开发新纪元——Accordion控件、图表功能升级...
  4. linux 特定用户ssh,linux - 如何在登录后将SSH用户限制为一组预定义的命令?
  5. 使用IntelliJ IDEA开发SpringMVC网站(五)博客文章管理
  6. 正则表达式 以字符串开头_干货-Shell编程之正则表达式
  7. 疑难杂症 | Win10解压文件后乱码
  8. intel wifi 5100agn linux驱动,intel5100agn驱动
  9. 用PS调出二次元风格水彩漫画风景图片
  10. html桌面插件,js桌面虚拟键盘插件A-Keyboard
  11. 文献检索与阅读技巧:如何高效的阅读和学习论文文献
  12. 十年磨一剑-企业核心竞争力的重塑
  13. C语言 单片机 快速计算COS SIN
  14. 【人工智能项目】深度学习实现汉字书法识别
  15. Windows Azure案例:迈阿密市政府使用“云”平台改善服务方案,降低运营成本
  16. 小米汽车设计图纸泄露,官方称非最终文件;微软裁员遣散费高达8亿美元,人均获赔54万元;苹果暂停自研Wi-Fi芯片|极客头条
  17. windows上如何安装Sqlite
  18. HTML5新增属性nofollow标签的应用场景
  19. 如何将网页中的Print2Flash文件下载下来,并用网页打开swf格式文件?
  20. PostgreSQL安装以及和mysql的对比

热门文章

  1. 过了初试,面试而不了了之
  2. 30多岁的男人是创业,还是选择找个踏实的工作?
  3. “不管什么关系,只要提借钱,千万别借”你怎么看?
  4. 现在很多人都做自媒体,谈谈个人的一些想法
  5. 新入行的包工头,一定做好下面几点
  6. Jenkins发布PHP项目之一自动化部署
  7. Apple’s current market value is more than two trillion
  8. 简单了解 Tendermint
  9. 类的声明、成员的访问控制和对象
  10. vscode使用相关配置