Trie

The formal way to implement trie tree is to define a trie node first. However using Python, there is a more faster way to do so.

Faster way (Python):

class Trie(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.trie = {}

    def insert(self, word):
        """
        Inserts a word into the trie.
        :type word: str
        :rtype: void
        """

        trie = self.trie

        for w in word:
            if w not in trie:
                trie[w] = {}
            trie = trie[w]

        trie['#'] = True   # <--- this is the trick

    def search(self, word):
        """
        Returns if the word is in the trie.
        :type word: str
        :rtype: bool
        """

        trie = self.trie

        for w in word:
            if w not in trie:
                return False
            trie = trie[w]

        return '#' in trie  # <--- this is the trick

    def startsWith(self, prefix):
        """
        Returns if there is any word in the trie that starts with the given prefix.
        :type prefix: str
        :rtype: bool
        """

        trie = self.trie

        for w in prefix:
            if w not in trie:
                return False
            trie = trie[w]

        return True

Standard way (C++):

class TrieNode {
public:
    TrieNode *child[26];
    bool is_word;
    TrieNode(bool b = false) {
        for (auto &a : child) a = NULL;    
        is_word = b;
    }
};

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

    /** Inserts a word into the trie. */
    void insert(string word) {
        TrieNode *p = root;

        for (int i = 0; i < word.size(); i++) {
            if (p->child[word[i] - 'a'] == NULL) {
                p->child[word[i] - 'a'] = new TrieNode();
            }
            p = p->child[word[i] - 'a'];
        }
        p->is_word = true;
    }

    /** Returns if the word is in the trie. */
    bool search(string word) {
        TrieNode *p = root;

        for (int i = 0; i < word.size(); i++) {
            if (p->child[word[i] - 'a'] == NULL) {
                return false;
            }
            p = p->child[word[i] - 'a'];
        }

        return p->is_word == true;

    }

    /** Returns if there is any word in the trie that starts with the given prefix. */
    bool startsWith(string prefix) {
        TrieNode *p = root;

        for (int i = 0; i < prefix.size(); i++) {
            if (p->child[prefix[i] - 'a'] == NULL) {
                return false;
            }
            p = p->child[prefix[i] - 'a'];
        }

        return true;
    }
};

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

results matching ""

    No results matching ""