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");
  • 相关阅读:
    JDBC
    两道关于回溯法,分支限界法的算法题
    旅行售货员问题
    jdbc学习
    mysql简单练习
    取会邮件客户端中的密码
    触发器的使用
    事务的数据一致性测试
    读取其他软件listview控件的内容
    sqlserver2008 ,只能选C盘目录,不能选其它盘目录
  • 原文地址:https://www.cnblogs.com/argenbarbie/p/5416928.html
Copyright © 2011-2022 走看看