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

    class Node {
    public:
        char c;
        bool isWord;
        unordered_map<char,Node*> children;
        Node(char c) {
            this->c = c;
            isWord = false;
        }
    };
    class Trie {
        Node* root;
        
        Node* findString(string s) {
            Node* p = root;
            for (int i = 0; i < s.length(); i++) {
                if (!p->children.count(s[i]))
                    return NULL;
                p = p->children[s[i]];
            }
            return p;
        }
    public:
        /** Initialize your data structure here. */
        Trie() {
            root = new Node(0);
        }
        
        /** Inserts a word into the trie. */
        void insert(string word) {
            Node* p = root;
            for (int i = 0; i < word.length(); i++) {
                if (!p->children.count(word[i]))
                    p->children[word[i]] = new Node(word[i]);
                p = p->children[word[i]];
            }
            p->isWord = true;
        }
        
        /** Returns if the word is in the trie. */
        bool search(string word) {
            Node* p = findString(word);
            return p != NULL && p->isWord;
        }
        
        /** Returns if there is any word in the trie that starts with the given prefix. */
        bool startsWith(string prefix) {
            Node* p = findString(prefix);
            return p != NULL;
        }
    };
    
    /**
     * Your Trie object will be instantiated and called as such:
     * Trie obj = new Trie();
     * obj.insert(word);
     * bool param_2 = obj.search(word);
     * bool param_3 = obj.startsWith(prefix);
     */
  • 相关阅读:
    Python下用Tkinter进行GUI编程
    6月3日——回首一个半月
    Consistent Hashing算法
    学生终究要面对社会
    MySQL的锁(1)
    Memcached笔记之分布式算法(idv2.com)
    4月21日总结
    2012.3.29小结
    C#调用c++创建的dll
    以post方式发送文档到端口
  • 原文地址:https://www.cnblogs.com/JTechRoad/p/9065709.html
Copyright © 2011-2022 走看看