LeetCode "Add and Search Word

I'm glad to see that LeetCode has finally realized the importance of Trie.

My C++ code can be further optimized..

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 WordDictionary {
public:
    WordDictionary() 
    {
        root = new TrieNode();
    }
    
    ~WordDictionary()
    {
        if (root)    delete root;
    }
    // Adds a word into the data structure.
    void addWord(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 data structure. A word could
    // contain the dot character '.' to represent any one letter.
    bool search(string key) {
        return _search(key, *root);
    }

private:
    bool _search(string sub, TrieNode &r)
    {
        if(sub.empty()) return true;
        if(sub.length() == 1)
        {
            if (sub[0] == '.')
            {
                for (auto &n : r.childMap)
                    if(n.second.bIsLast) 
                        return true;
                return false;
            }
            else 
            {
                return r.childMap.find(sub[0]) != r.childMap.end() && r.childMap[sub[0]].bIsLast;
            }
        }

        for(int i = 0; i < sub.length(); i ++)
        {
            char c = sub[i];
            string ss = sub.substr(i + 1);
            if (c == '.')
            {
                for (auto &n : r.childMap)
                    if(_search(ss, n.second)) 
                        return true;
                return false;
            }
            else        
            {
                if(r.childMap.find(c) != r.childMap.end())
                    return _search(ss, r.childMap[c]);                    
                
                return false;
            }
        }
        
        return false;
    }
    TrieNode* root;
};
View Code
原文地址:https://www.cnblogs.com/tonix/p/4516111.html