zoukankan      html  css  js  c++  java
  • 208. Implement Trie (Prefix Tree) -- 键树

    Implement a trie with insertsearch, and startsWith methods.

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

    class TrieNode {
    public:
        // Initialize your data structure here.
        bool isWord;
        unordered_map<char, TrieNode*> alpha;
        TrieNode():isWord(false) {}
    };
    
    class Trie {
    public:
        Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        void insert(string word) {
            TrieNode *p = root;
            int l = word.length(), i;
            for(i = 0; i < l; i++)
            {
                if(p->alpha.find(word[i]) == p->alpha.end())
                {
                    TrieNode *t = new TrieNode();
                    p->alpha[word[i]] = t;
                }
                p = p->alpha[word[i]];
            }
            p->isWord = true;
        }
    
        // Returns if the word is in the trie.
        bool search(string word) {
            TrieNode *p = root;
            int l = word.length(), i;
            for(i = 0; i < l; i++)
            {
                if(p->alpha.find(word[i]) == p->alpha.end())
                    return false;
                p = p->alpha[word[i]];
            }
            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;
            int l = prefix.length(), i;
            for(i = 0; i < l; i++)
            {
                if(p->alpha.find(prefix[i]) == p->alpha.end())
                    return false;
                p = p->alpha[prefix[i]];
            }
            return true;
        }
    
    private:
        TrieNode* root;
    };
    
    // Your Trie object will be instantiated and called as such:
    // Trie trie;
    // trie.insert("somestring");
    // trie.search("key");
  • 相关阅读:
    [ASP.NET] 使用 ASP.NET SignalR 添加实时 Web
    [ORM] Entity Framework(2) CodeFirst进阶
    [ORM] Entity Framework(1) CodeFirst快速入门
    [C#] 谈谈异步编程async await
    [Solution] NPOI操作Excel
    消息队列二
    消息队列一
    redis成长之路——(七)
    redis成长之路——(六)
    redis成长之路——(五)
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5416928.html
Copyright © 2011-2022 走看看