[LeetCode] Design Add and Search Words Data Structure

211. Design Add and Search Words Data Structure

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.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Trie {
public:
unordered_map<char, Trie*> child;
bool endOfWord = false;
void createChild(char c) {
child[c] = new Trie();
}
};

class WordDictionary {
Trie* root = new Trie();
bool _search(const char* word, Trie* node) {
for(int i = 0; node && word[i]; i++) {
if(word[i] != '.') {
if(!node->child.count(word[i])) return false;
node = node->child[word[i]];
} else {
for(auto t : node->child) {
if(_search(word + i + 1, t.second)) return true;
}
return false;
}
}
return node && node->endOfWord;
}
public:
/** Initialize your data structure here. */
WordDictionary() {}

void addWord(string word) {
Trie* node = root;
for(auto& c : word) {
if(!node->child.count(c)) node->createChild(c);
node = node->child[c];
}
node->endOfWord = true;
}

bool search(string word) {
return _search(word.c_str(), root);
}
};

/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/05/23/PS/LeetCode/design-add-and-search-words-data-structure/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.