LeetCode 208. Implement Trie (Prefix Tree)

https://leetcode.com/problems/implement-trie-prefix-tree/description/

Implement a trie with insertsearch, and startsWith methods.

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


  • Trie,前缀树,字典树。Solution里提供了详细的数据结构和算法实现。由于用到指针数组,注意初始化指针,以及析构函数防止内存泄漏问题。
  • Implement Trie (Prefix Tree) - LeetCode
    • https://leetcode.com/problems/implement-trie-prefix-tree/solution/
    • https://leetcode.com/problems/implement-trie-prefix-tree/discuss/58842/Maybe-the-code-is-not-too-much-by-using-%22next26%22-C++
  • 字典树_百度百科
    • https://baike.baidu.com/item/字典树/9825209?fromtitle=Trie树&fromid=517527
    • 又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。
  • Trie - 维基百科,自由的百科全书
    • https://zh.wikipedia.org/wiki/Trie
    • 计算机科学中,trie,又称前缀树字典树,是一种有序,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值。
  1 //
  2 //  main.cpp
  3 //  LeetCode
  4 //
  5 //  Created by Hao on 2017/3/16.
  6 //  Copyright © 2017年 Hao. All rights reserved.
  7 //
  8 
  9 #include <iostream>
 10 using namespace std;
 11 
 12 class TrieNode {
 13 public:
 14     TrieNode() : isEnd(false) {
 15         memset(links, 0, sizeof(links)); // remember for inialization
 16     }
 17     
 18     ~TrieNode() {                        // remember to avoid memory leak
 19         for (auto & iter : links)
 20             delete iter;
 21     }
 22     
 23     bool containsKey(char ch) {
 24         return links[ch - 'a'] != nullptr;
 25     }
 26     
 27     TrieNode* get(char ch) {
 28         return links[ch - 'a'];
 29     }
 30     
 31     void put(char ch, TrieNode* node) {
 32         links[ch - 'a'] = node;
 33     }
 34     
 35     void setEnd() {
 36         isEnd = true;
 37     }
 38     
 39     bool getEnd() {
 40         return isEnd;
 41     }
 42     
 43 private:
 44     TrieNode*   links[26];
 45     bool        isEnd;
 46 };
 47 
 48 class Trie {
 49 public:
 50     /** Initialize your data structure here. */
 51     Trie() {
 52         root = new TrieNode;
 53     }
 54     
 55     ~Trie() {                           // remember to avoid memory leak
 56         delete root;
 57     }
 58     
 59     /** Inserts a word into the trie. */
 60     void insert(string word) {
 61         TrieNode* node = root;
 62         
 63         for (int i = 0; i < word.size(); i ++) {
 64             char currentChar = word.at(i);
 65             
 66             if (! node->containsKey(currentChar)) {
 67                 node->put(currentChar, new TrieNode());
 68             }
 69             
 70             node = node->get(currentChar);
 71         }
 72         
 73         node->setEnd();
 74     }
 75     
 76     /** Returns if the word is in the trie. */
 77     bool search(string word) {
 78         TrieNode* node = searchPrefix(word);
 79         
 80         return node != nullptr && node->getEnd();
 81     }
 82     
 83     /** Returns if there is any word in the trie that starts with the given prefix. */
 84     bool startsWith(string prefix) {
 85         TrieNode* node = searchPrefix(prefix);
 86         
 87         return node != nullptr;
 88     }
 89     
 90 private:
 91     TrieNode* searchPrefix(string word) {
 92         TrieNode* node = root;
 93         
 94         for (int i = 0; i < word.size(); i ++) {
 95             char currentChar = word.at(i);
 96             
 97             if (node->containsKey(currentChar)) {
 98                 node = node->get(currentChar);
 99             } else {
100                 return nullptr;
101             }
102         }
103         
104         return node;
105     }
106 
107     TrieNode*   root;
108 };
109 
110 /**
111  * Your Trie object will be instantiated and called as such:
112  * Trie obj = new Trie();
113  * obj.insert(word);
114  * bool param_2 = obj.search(word);
115  * bool param_3 = obj.startsWith(prefix);
116  */
117 
118 int main(int argc, char* argv[])
119 {
120     Trie obj;
121     
122     obj.insert("word");
123     bool param_2 = obj.search("word");
124     bool param_3 = obj.startsWith("wo");
125     bool param_4 = obj.startsWith("prefix");
126 
127     /*
128      1
129      1
130      0
131      */
132     cout << param_2 << endl;
133     cout << param_3 << endl;
134     cout << param_4 << endl;
135 
136     return 0;
137 }
View Code

 

posted on 2018-02-22 18:07  浩然119  阅读(186)  评论(0编辑  收藏  举报