Cover image for Interview Classic 150 Questions P211 Add and Search Word - Data Structure Design

Interview Classic 150 Questions P211 Add and Search Word - Data Structure Design


Timeline

Timeline

2025-11-24

init

Trie

Title:

Recursive implementation, ifword[i]is wildcard ‘.’, then start from all child nodes of the current Trie node, searchword.substr(i+1, n-i-1), and whenword[i]=='.'andi==n-1when, at this point it is the last node, the last node is a wildcard, so we only need to check whether the current node’s children haveis_end==trueof

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <string>
#include <vector>
using std::string;
using std::vector;

typedef struct TrieNode {
vector<struct TrieNode *> children;
int data;
bool is_end;
} TrieNode;

class WordDictionary {
private:
TrieNode *root;

public:
WordDictionary()
{
root = new TrieNode;
root->children = vector<struct TrieNode *>(26, nullptr);
root->is_end = false;
}

void addWord(string word)
{
TrieNode *p = root, *node;
int i = 0, n = word.size();
int curr;
for (i = 0; i < n; i++) {
curr = word[i] - 'a';
if (p->children[curr] != nullptr) {
p = p->children[curr];
continue;
}
node = new TrieNode;
node->children = vector<struct TrieNode *>(26, nullptr);
node->data = curr;
node->is_end = false;
p->children[curr] = node;
p = node;
}
p->is_end = true;
}
bool searchImpl(string word, TrieNode *root)
{
TrieNode *p = root;
int i = 0, n = word.size(), curr;
for (i = 0; i < n; i++) {
if (word[i] != '.') {
curr = word[i] - 'a';
if (p->children[curr] != nullptr) {
p = p->children[curr];
continue;
}
return false;

} else {
for (TrieNode *child : p->children) {
if (child == nullptr) {
continue;
}
if (i == n - 1 && child->is_end) {
return true;
}
if (searchImpl(word.substr(i + 1, n - i - 1), child)) {
return true;
}
}
return false;
}
}

return p->is_end;
}
bool search(string word)
{
return searchImpl(word, root);
}
};

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