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

    Trie 树模板

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

    class TrieNode {
    public:
        char var;
        bool isWord;
        TrieNode *next[26];
        TrieNode() {
            var = 0;
            this->isWord = false;
            for(auto &c : next) c = NULL;
        }
        TrieNode(char c) {
            var = c;
            this->isWord = false;
            for(auto &c : next) c = NULL;
        }
    };
    
    class Trie {
    public:
        Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        void insert(string word) {
            TrieNode *p = root;
            for(auto &a : word) {
                int idx = a - 'a';
                if(!p->next[idx]) p->next[idx] = new TrieNode();
                p = p->next[idx];
            }
            p->isWord = true;
        }
    
        // Returns if the word is in the trie.
        bool search(string word) {
            TrieNode *p = root;
            for(auto &a : word) {
                int idx = a - 'a';
                if(!p->next[idx]) return false;
                p = p->next[idx];
            }
            return p->isWord;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        bool startsWith(string prefix) {
            TrieNode *p = root;
            for(auto &a : prefix) {
                int idx = a - 'a';
                if(!p->next[idx]) return false;
                p = p->next[idx];
            }
            return true;        
        }
    
    private:
        TrieNode* root;
    };
    
    // Your Trie object will be instantiated and called as such:
    // Trie trie;
    // trie.insert("somestring");
    // trie.search("key");
  • 相关阅读:
    安装mysql
    工坊第十天
    工坊第九天
    友链qaq
    About me
    好耶
    [Ynoi2011]初始化
    [Ynoi2013]大学
    [Ynoi2015]盼君勿忘
    [Ynoi2019模拟赛]Yuno loves sqrt technology III
  • 原文地址:https://www.cnblogs.com/fu11211129/p/4952245.html
Copyright © 2011-2022 走看看