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

猜你喜欢

转载自www.cnblogs.com/JTechRoad/p/9065709.html