LeetCode-208 Implement Trie (Prefix Tree)

Title Description

Implement a trie with insertsearch, and startsWith methods.

 

Subject to the effect

Find realize the operation of the insert, search, and a prelude to a tree.

(Each tree node represents a lowercase letter, a complete word from the root to the leaf nodes represent)

 

Examples

E

Trie trie = new Trie();

trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true

 

Problem-solving ideas

Thanks thinking Leetcode @ cxq1992 provided, the method of engineering a more complete record keeping and operating tree node.

 

Complexity Analysis

Time complexity: O (NULL)

Space complexity: O (NULL)

 

Code

class node {
public:
    node() : val(' '), end(false), shared(0) {}
    node(char c) : val(c), end(false), shared(0) {}
    node* subchild(char c) {
        if(!child.empty()) {
            for(auto chi : child) {
                if(chi->val == c)
                    return chi;
            }
        }
        
        return NULL;
    }
    ~node() {
        for(auto chi : child)
            delete chi;
    }
    // The node tree stored lowercase 
    char Val;
     // whether the node is a leaf node 
    BOOL End;
     // number of child nodes 
    int Shared;
     // child node stores 
    Vector <Node *> Child;
};

class Trie {
public:
    /** Initialize your data structure here. */
    Trie() {
        root = new node();
    }
    
    /** Inserts a word into the trie. */
    void insert(string word) {
        if(search(word))
            return;
        node* cur = root;
        for(char c : word) {
            node* tmp = cur->subchild(c);
            if(tmp == NULL) {
                tmp = new node(c);
                cur->child.push_back(tmp);
                cur = tmp;
            }
            else {
                cur = tmp;
            }
            ++cur->shared;
        }
        cur->end = true;
    }
    
    /** Returns if the word is in the trie. */
    bool search(string word) {
        node* tmp = root;
        for(char c : word) {
            tmp = tmp->subchild(c);
            if(tmp == NULL)
                return false;
        }
        
        return tmp->end;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        node* tmp = root;
        for(char c : prefix) {
            tmp = tmp->subchild(c);
            if(tmp == NULL)
                return false;
        }
        
        return true;
    }
    
private:
    node* root;
};

/**
 * 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);
 */

 

Guess you like

Origin www.cnblogs.com/heyn1/p/11016344.html