Implement Trie

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

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

Using hash table

  • To save words in trie, we need add a bool to indicate if the current node represents a word.
  • When inserting a word in trie, remember to mark the value at the trail node as true.
class TrieNode {
public:
    bool hasWord;
    unordered_map<char, TrieNode*> children;

    TrieNode() : hasWord(false) {};
    TrieNode(char c): c(c), hasWord(false) {};
};

class Trie {
public:
    /** Initialize your data structure here. */
    Trie() {
        root = new TrieNode();
    }

    /** Inserts a word into the trie. */
    void insert(string word) {
        TrieNode *cur = root;
        for (auto ch: word) {
            if (!cur->children.count(ch)) {
                cur->children[ch] = new TrieNode();
            }
            cur = cur->children[ch];
        }
        cur->hasWord = true;
    }

    /** Returns if the word is in the trie. */
    bool search(string word) {
        TrieNode *node = searchWordNodePos(word);
        if (!node) return false;
        return node->hasWord == true;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        return searchWordNodePos(prefix) != NULL;
    }

    TrieNode* searchWordNodePos(string s) {
        TrieNode *cur = root;
        for (auto ch: s) {
            if (!cur->children.count(ch)) return NULL;
            cur = cur->children[ch];
        }
        return cur;
    }

private:
    TrieNode *root;
};

Using Array

class TrieNode {
public:
    bool hasWord;
    TrieNode* children[26];

    TrieNode() {
        hasWord = false;
        for (int i=0; i<26; i++) children[i] = NULL;
    };
};

class Trie {
public:
    /** Initialize your data structure here. */
    Trie() {
        root = new TrieNode();
    }

    /** Inserts a word into the trie. */
    void insert(string word) {
        TrieNode *cur = root;
        for (auto ch: word) {
            if (!cur->children[ch-'a']) {
                cur->children[ch-'a'] = new TrieNode();
            }
            cur = cur->children[ch-'a'];
        }        
        cur->hasWord = true;
    }

    /** Returns if the word is in the trie. */
    bool search(string word) {
        TrieNode *node = searchWordNodePos(word);
        if (!node) return false;
        return node->hasWord == true;
    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        return searchWordNodePos(prefix) != NULL;
    }

    TrieNode* searchWordNodePos(string s) {
        TrieNode *cur = root;
        for (auto ch: s) {
            if (!cur->children[ch-'a']) return NULL;
            cur = cur->children[ch-'a'];
        }
        return cur;
    }

private:
    TrieNode *root;
};

results matching ""

    No results matching ""