实现一个 Trie (前缀树),包含 insert, search, 和 startsWith 这三个方法。
注意:
你可以假设所有的输入都是小写字母 a-z。
详见:https://leetcode.com/problems/implement-trie-prefix-tree/description/

Java实现:

Trie树,又称为字典树、单词查找树或者前缀树,是一种用于快速检索的多叉数结构。例如,英文字母的字典树是26叉数,数字的字典树是10叉树。
Trie树的基本性质有三点,归纳为:
根节点不包含字符,根节点外每一个节点都只包含一个字符。
从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。
每个节点的所有子节点包含的字符串不相同。
insert:分析单词的每一个字符,如果存在与已经有的孩子中,则循环转到该孩子节点,否则新建孩子节点,最后在单词的末尾字符isWord标志位true;
search: 逐个分析每个字符,如果不存在该字符的孩子则返回false,否则循环之后,查看末尾字符的标志位即可;
prefix: 和search一样,只是在最后只要是都存在每个字符相应的孩子map,则返回true。

  1. class TrieNode{
  2. boolean isWord;
  3. HashMap<Character,TrieNode> map;
  4. public TrieNode(){
  5. map=new HashMap<Character,TrieNode>();
  6. }
  7. }
  8. class Trie {
  9. private TrieNode root;
  10.  
  11. /** Initialize your data structure here. */
  12. public Trie() {
  13. root=new TrieNode();
  14. }
  15.  
  16. /** Inserts a word into the trie. */
  17. public void insert(String word) {
  18. char[] charArray=word.toCharArray();
  19. TrieNode tmp=root;
  20. for(int i=0;i<charArray.length;++i){
  21. if(!tmp.map.containsKey(charArray[i])){
  22. tmp.map.put(charArray[i],new TrieNode());//添加
  23. }
  24. tmp=tmp.map.get(charArray[i]);//转到孩子节点
  25. if(i==charArray.length-1){//末尾字符
  26. tmp.isWord=true;
  27. }
  28. }
  29. }
  30.  
  31. /** Returns if the word is in the trie. */
  32. public boolean search(String word) {
  33. TrieNode tmp=root;
  34. for(int i=0;i<word.length();++i){
  35. TrieNode next=tmp.map.get(word.charAt(i));
  36. if(next==null){
  37. return false;
  38. }
  39. tmp=next;
  40. }
  41. return tmp.isWord;
  42. }
  43.  
  44. /** Returns if there is any word in the trie that starts with the given prefix. */
  45. public boolean startsWith(String prefix) {
  46. TrieNode tmp=root;
  47. for(int i=0;i<prefix.length();++i){
  48. TrieNode next=tmp.map.get(prefix.charAt(i));
  49. if(next==null){
  50. return false;
  51. }
  52. tmp=next;
  53. }
  54. return true;
  55. }
  56. }
  57.  
  58. /**
  59. * Your Trie object will be instantiated and called as such:
  60. * Trie obj = new Trie();
  61. * obj.insert(word);
  62. * boolean param_2 = obj.search(word);
  63. * boolean param_3 = obj.startsWith(prefix);
  64. */

C++实现:

  1. class TrieNode
  2. {
  3. public:
  4. TrieNode *next[26];
  5. char c;
  6. bool isWord;
  7. TrieNode():isWord(false)
  8. {
  9. memset(next,0,sizeof(TrieNode*)*26);
  10. }
  11. TrieNode(char _c):c(_c),isWord(false)
  12. {
  13. memset(next,0,sizeof(TrieNode*)*26);
  14. }
  15. };
  16. class Trie {
  17. public:
  18. /** Initialize your data structure here. */
  19. Trie() {
  20. root=new TrieNode();
  21. }
  22.  
  23. /** Inserts a word into the trie. */
  24. void insert(string word) {
  25. TrieNode *p=root;
  26. int id;
  27. for(char c:word)
  28. {
  29. id=c-'a';
  30. if(p->next[id]==nullptr)
  31. {
  32. p->next[id]=new TrieNode(c);
  33. }
  34. p=p->next[id];
  35. }
  36. p->isWord=true;
  37. }
  38.  
  39. /** Returns if the word is in the trie. */
  40. bool search(string word) {
  41. TrieNode *p=root;
  42. int id;
  43. for(char c:word)
  44. {
  45. id=c-'a';
  46. if(p->next[id]==nullptr)
  47. {
  48. return false;
  49. }
  50. p=p->next[id];
  51. }
  52. return p->isWord;
  53. }
  54.  
  55. /** Returns if there is any word in the trie that starts with the given prefix. */
  56. bool startsWith(string prefix) {
  57. TrieNode *p=root;
  58. int id;
  59. for(char c:prefix)
  60. {
  61. id=c-'a';
  62. if(p->next[id]==nullptr)
  63. {
  64. return false;
  65. }
  66. p=p->next[id];
  67. }
  68. return true;
  69. }
  70. private:
  71. TrieNode *root;
  72. };
  73.  
  74. /**
  75. * Your Trie object will be instantiated and called as such:
  76. * Trie obj = new Trie();
  77. * obj.insert(word);
  78. * bool param_2 = obj.search(word);
  79. * bool param_3 = obj.startsWith(prefix);
  80. */

208 Implement Trie (Prefix Tree) 字典树(前缀树)的更多相关文章

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

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

  2. LeetCode 208 Implement Trie (Prefix Tree) 字典树(前缀树)

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

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

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

  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)

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

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

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

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

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

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

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

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

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

随机推荐

  1. C++卷积神经网络实例:tiny_cnn代码具体解释(6)——average_pooling_layer层结构类分析

    在之前的博文中我们着重分析了convolutional_layer类的代码结构.在这篇博文中分析相应的下採样层average_pooling_layer类: 一.下採样层的作用 下採样层的作用理论上来 ...

  2. Android修改签名

    #!/bin/shtmp=~/temp.apkcp "$1" "$tmp"zip -d "$tmp" META-INF/\*jarsigne ...

  3. (原创)EasyUI中datagrid的行编辑模式中,找到特定的Editor,并为其添加事件

    有时候在行编辑的时候,一个编辑框的值要根据其它编辑框的值进行变化,那么可以通过在开启编辑时,找到特定的Editor,为其添加事件 // 绑定事件, index为当前编辑行 var editors = ...

  4. Hibernate 之 一级缓存

    本篇文章主要是总结Hibernate中关于缓存的相关内容. 先来看看什么是缓存,我们这里所说的缓存主要是指应用程序与物流数据源之间(例如硬盘),用于存放临时数据的内存区域,这样做的目的是为了减少应用程 ...

  5. Java正则表达式的用法

    /** * 校验时间格式,正确则返回true * @param xxx * @return */ private static boolean checkDateFormat (String xxx) ...

  6. Buildroot用户指南【转】

    本文转载自:http://www.voidcn.com/blog/bytxl/article/p-4727302.html 第一章        关于Buildroot Buildroot是一个包含M ...

  7. YTU 1074: You are my brother

    1074: You are my brother 时间限制: 1 Sec  内存限制: 128 MB 提交: 10  解决: 7 题目描述 Little A gets to know a new fr ...

  8. Python之xlsx文件与csv文件相互转换

    1 xlsx文件转csv文件 import xlrd import csv def xlsx_to_csv(): workbook = xlrd.open_workbook('1.xlsx') tab ...

  9. Watir: 右键点击实例(某些如果应用AutoIt来做会更加简单高效)

    require 'watir' module Watir class Element def top_edge assert_exists assert_enabled ole_object.getB ...

  10. 【转】浏览器中输入url后发生了什么

    原文地址:http://www.jianshu.com/p/c1dfc6caa520 在学习前端的过程中经常看到这样一个问题:当你在浏览器中输入url后发生了什么?下面是个人学习过程中的总结,供个人复 ...