C++     Depth-First Search     Design     Medium     String     Trie    

Problem Statement:

Design a data structure that supports adding new words and finding if a string matches any previously added string.

Implement the WordDictionary class:

  • WordDictionary() Initializes the object.
  • void addWord(word) Adds word to the data structure, it can be matched later.
  • bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots '.' where dots can be matched with any letter.

 

Example:

Input
["WordDictionary","addWord","addWord","addWord","search","search","search","search"]
[[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]]
Output
[null,null,null,null,false,true,true,true]

Explanation
WordDictionary wordDictionary = new WordDictionary();
wordDictionary.addWord("bad");
wordDictionary.addWord("dad");
wordDictionary.addWord("mad");
wordDictionary.search("pad"); // return False
wordDictionary.search("bad"); // return True
wordDictionary.search(".ad"); // return True
wordDictionary.search("b.."); // return True

 

Constraints:

  • 1 <= word.length <= 25
  • word in addWord consists of lowercase English letters.
  • word in search consist of '.' or lowercase English letters.
  • There will be at most 2 dots in word for search queries.
  • At most 104 calls will be made to addWord and search.

Solution:

We use the standard Trie data structure. We modify the search method to handle the case when the search term contains ..

 
class Trie
{
    vector<Trie*> children;
    bool isEnd;
public:
    Trie(){children = vector<Trie*>(26,NULL); isEnd=false;}
    void add(string word, int index)
    {
        if (index==word.length()) {isEnd=true; return;}
        int pos = word[index]-'a';
        if (children[pos]==NULL) children[pos] = new Trie();
        children[pos]->add(word, index+1);
    }
    bool search(string word, int index)
    {
        if (index==word.length()) return isEnd;
        if (word[index]=='.')
        {
            for(int i=0; i<26; i++) if(children[i]!=NULL && \
                children[i]->search(word,index+1)) return true;
            return false;
        }
        int pos = word[index]-'a';
        if (children[pos]==NULL) return false;
        return children[pos]->search(word, index+1);
    }
};

class WordDictionary {
    Trie *trie;
public:
    WordDictionary() {trie = new Trie();}    
    void addWord(string word) {trie->add(word,0);}    
    bool search(string word) {return trie->search(word,0);}
};

/**
 * Your WordDictionary object will be instantiated and called as such:
 * WordDictionary* obj = new WordDictionary();
 * obj->addWord(word);
 * bool param_2 = obj->search(word);
 */