zoukankan      html  css  js  c++  java
  • [LeetCode] Implement Trie (Prefix Tree)

    You need to understand what a Trie is before writing the code :-) This link has a nice solution, whose code is rewritten below.

     1 class TrieNode {
     2 public:
     3     bool isWord;
     4     TrieNode* children[26];
     5     // Initialize your data structure here.
     6     TrieNode() : isWord(false) {
     7         memset(children, NULL, sizeof(TrieNode*) * 26);
     8     }
     9 };
    10 
    11 class Trie {
    12 public:
    13     Trie() {
    14         root = new TrieNode();
    15     }
    16 
    17     // Inserts a word into the trie.
    18     void insert(string word) {
    19         TrieNode* run = root;
    20         for (char c : word) {
    21             if (!(run -> children[c - 'a']))
    22                 run -> children[c - 'a'] = new TrieNode();
    23             run = run -> children[c - 'a'];
    24         }
    25         run -> isWord = true;
    26     }
    27 
    28     // Returns if the word is in the trie.
    29     bool search(string word) {
    30         TrieNode* p = query(word);
    31         return p && p -> isWord;
    32     }
    33 
    34     // Returns if there is any word in the trie
    35     // that starts with the given prefix.
    36     bool startsWith(string prefix) {
    37         return query(prefix);
    38     }
    39 
    40 private:
    41     TrieNode* root;
    42     TrieNode* query(string& s) {
    43         TrieNode* run = root;
    44         for (char c : s) {
    45             if (!(run -> children[c - 'a'])) return NULL;
    46             run = run -> children[c - 'a'];
    47         }
    48         return run;
    49     }
    50 };
    51 
    52 // Your Trie object will be instantiated and called as such:
    53 // Trie trie;
    54 // trie.insert("somestring");
    55 // trie.search("key");
  • 相关阅读:
    UVa 839 -- Not so Mobile(树的递归输入)
    UVa 548 -- Tree
    UVA 122 -- Trees on the level (二叉树 BFS)
    UVa679 小球下落(树)
    POJ 2255 -- Tree Recovery
    POJ 1451 -- T9
    POJ 2513 -- Colored Sticks
    STL -- heap结构及算法
    nginx利用try_files实现多个源
    nginx location的优先级
  • 原文地址:https://www.cnblogs.com/jcliBlogger/p/4737807.html
Copyright © 2011-2022 走看看