211 Add and Search Word - Data structure design

Design a data structure that supports the following two operations:

void addWord(word)
bool search(word)

search(word) can search a literal word or a regular expression string containing only letters a-z or '.' A '.' means it can represent any one letter.
For example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
  • Note: You may assume that all words are consist of lowercase letters a-z.

Solution

class WordDictionary {
    struct TreeNode{
        bool isEnd;
        unordered_map<char, TreeNode*> next;
        TreeNode(): isEnd(false){}
    };
public:
    TreeNode* root = new TreeNode();

    // Adds a word into the data structure.
    void addWord(string word) {
        TreeNode *p = root;
        int n = word.size();
        for ( int i = 0; i <= n-1; i++ ) {
            char c = word[i];
            if ( p->next.find(c) == p->next.end() ) {
                TreeNode *nextP = new TreeNode();
                p->next[c] = nextP;
                p = nextP;
            }
            else p = p->next[c];
        }
        // tag that this node is the end!
        p->isEnd = true;
        return;
    }

    // Returns if the word is in the data structure. A word could
    // contain the dot character '.' to represent any one letter.
    bool searchHelp(string s, TreeNode* p) {
        int n = s.size();
        if ( n == 0 ) return p->isEnd;
        if ( s[0] != '.' ) {
            if ( p->next.find(s[0]) == p->next.end() ) return false;
            return searchHelp(s.substr(1), p->next[s[0]]);
        }
        for ( auto it = p->next.begin(); it != p->next.end(); it++ ) {
            if ( searchHelp(s.substr(1), it->second) ) return true;
        }
        return false;
    }
    bool search(string word) {
        TreeNode *p = root;
        return searchHelp(word, p);
    }
};

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");

Notes
Note to use a bool variable to tag whether current node is the end of a word!

results matching ""

    No results matching ""