Tuesday 20 September 2016

Implement Trie / Prefix Tree (leetcode)

Problem: 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.

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

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

    // Inserts a word into the trie.
    void insert(string word) {
        TrieNode *head = root;
        
        int sl=word.length();
        for(int i=0;i<sl;i++)
        {
            int index = word[i] - 'a';
            if(head->child[index]==NULL)
                head->child[index] = new TrieNode();
            head->child[index]->countPrefix++;
            head = head->child[index];
        }
        head->isEnd=true;
    }

    // Returns if the word is in the trie.
    bool search(string word) {
        TrieNode *head = getLastNode(word);
        if(head==NULL) return false;
        return head->isEnd;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode *head = getLastNode(prefix);
        if(head==NULL) return false;
        if(head->countPrefix) return true;
        return false;
    }
    
    TrieNode* getLastNode(string s)
    {
        TrieNode *head = root;
        
        int sl=s.length();
        for(int i=0;i<sl;i++)
        {
            int index = s[i]-'a';
            if(head->child[index]==NULL)
                return NULL;
            head = head->child[index];
        }
        return head;
    }

private:
    TrieNode* root;
};

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

No comments:

Post a Comment