LeetCode "Implement Trie (Prefix Tree)"

Implementation problem.

class TrieNode {
public:
    // Initialize your data structure here.
    TrieNode() {
        c = 0;
        bIsLast = false;
    }
    TrieNode(char vc) {
        c = vc;
        bIsLast = false;
    }
public:
    char c;
    bool bIsLast;
    map<char, TrieNode> childMap;
};

class Trie {
public:
    Trie() 
    {
        root = new TrieNode();
    }
    
    ~Trie()
    {
        if (root)
            delete root;
    }
    
    // Inserts a word into the trie.
    void insert(string s) {
        TrieNode *r = root;
        for (int i = 0; i < s.length(); i++)
        {
            if (r->childMap.find(s[i]) == r->childMap.end())
            {
                r->childMap.insert(make_pair(s[i], TrieNode(s[i])));
            }
            
            r = &(r->childMap[s[i]]);            
        }
        r->bIsLast = true;
    }

    // Returns if the word is in the trie.
    bool search(string key) {
        TrieNode *r = root;
        for (int i = 0; i < key.length(); i++)
        {
            if (r->childMap.find(key[i]) == r->childMap.end())
            {
                return false;
            }

            r = &(r->childMap[key[i]]);
        }

        return r->bIsLast;
    }

    // Returns if there is any word in the trie
    // that starts with the given prefix.
    bool startsWith(string prefix) {
        TrieNode *r = root;
        for (int i = 0; i < prefix.length(); i++)
        {
            if (r->childMap.find(prefix[i]) == r->childMap.end())
            {
                return false;
            }

            r = &(r->childMap[prefix[i]]);
        }
        return true;
    }

private:
    TrieNode* root;
};
原文地址:https://www.cnblogs.com/tonix/p/4500154.html