C++ code with map


  • 0
    S
    class TrieNode {
    public:
        bool isWord;
        map<char, TrieNode*> nodes;
        // Initialize your data structure here.
        TrieNode() {
            isWord = false;
        }
    };
    
    class Trie {
    public:
        Trie() {
            root = new TrieNode();
        }
    
        // Inserts a word into the trie.
        void insert(string word) {
            TrieNode* node = root;
            for(int i=0; i<word.length(); i++)
            {
                if(node->nodes[word[i]] == NULL)
                    node->nodes[word[i]] = new TrieNode();
                node = node->nodes[word[i]];
                if(i == (word.length()-1))
                    node->isWord = true;
            }
        }
    
        // Returns if the word is in the trie.
        bool search(string word) {
            TrieNode* node = root;
            for(char c : word)
            {
                node = node->nodes[c];
                if(!node)
                    return false;
            }
            return node->isWord;
        }
    
        // Returns if there is any word in the trie
        // that starts with the given prefix.
        bool startsWith(string prefix) {
            TrieNode* node = root;
            for(char c : prefix)
            {
                node = node->nodes[c];
                if(!node)
                    return false;
            }
            return true;
        }
    
    private:
        TrieNode* root;
    };

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.