Simple c++ solution


  • 0
    I
    class WordDictionary {
    public:
    struct TrieNode {
        TrieNode() : isSubstantial(false) {};
        TrieNode* kids[26] = { 0 };
        bool isSubstantial;
    };
    
    // Adds a word into the data structure.
    void addWord(string word) {
        TrieNode *cur = root;
        for (int i = 0; i < word.size(); i++) {
            if (cur->kids[word[i] - 'a'] == NULL) {
                cur->kids[word[i] - 'a'] = new TrieNode();
            }
            cur = cur->kids[word[i] - 'a'];
        }
        cur->isSubstantial = true;
    }
    
    bool help(string word, TrieNode *cur) {
        for (int i = 0; i < word.size() && cur; i++) {
            if (word[i] == '.') {
                string subword = word.substr(i + 1);
                for (int j = 0; j < 26; j++) {
                    if (help(subword, cur->kids[j])) return true;
                }
                return false;
            } else {
                cur = cur->kids[word[i] - 'a'];
            }
        }
        return cur && cur->isSubstantial;
    }
    
    // Returns if the word is in the data structure. A word could
    // contain the dot character '.' to represent any one letter.
    bool search(string word) {
        return help(word, root);
    }
    
    private:
    TrieNode *root = new TrieNode();
    };

Log in to reply
 

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