[leetcode]Implement Trie (Prefix Tree)


Implement Trie (Prefix Tree)

Implement a trie with insert, search, and startsWith methods.

Note:
You may assume that all inputs are consist of lowercase letters a-z.

Use TrieNode * child[26] to denote 26 possible successors.

Use count to denote the number of words that end at current node.

If count == 0, no one ends at current node, this node is just a middle char of some stirngs.

If count > 0, some words end at current node.

class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode * child[26];
    int count;
    TrieNode() {
        for(int i = 0;i < 26; i++){
            child[i] = nullptr;
        }
        count = 0;
    }
};

class Trie {
public:
    Trie() {
        root = new TrieNode();
    }

    // Inserts a word into the trie.
    void insert(string word) {
        TrieNode * p = root;
        for(char c : word){
            int i = c - 'a';
            if(p->child[i] == nullptr){
                p->child[i] = new TrieNode();
            }
            p = p->child[i];
        }
        p->count++;
    }

    // Returns if the word is in the trie.
    bool search(string word) {
        TrieNode * p = root;
        for(char c : word){
            int i = c - 'a';
            if(p->child[i] == nullptr){
                return false;
            }
            p = p->child[i];
        }
        return p->count > 0;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode * p = root;
        for(char c : prefix){
            int i = c - 'a';
            if(p->child[i] == nullptr){
                return false;
            }
            p = p->child[i];
        }
        return true;
    }

private:
    TrieNode* root;
};

// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");

 

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.