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");
  • 相关阅读:
    docker常用操作
    docker-vlanhost
    打补丁说明
    mycat RULEs
    头晕的android SDK Manager and 找不到真机
    高格-一些特点的话题【抛入抛出关联】
    流程配置中心中的委托设置无法查看全部流程的问题
    验证flash player 是否正常
    kdpkg安装包解压
    go新环境Mac安装,包含okexchain
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5416928.html
Copyright © 2011-2022 走看看