-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaddsearchword_trie.cpp
80 lines (71 loc) · 1.93 KB
/
addsearchword_trie.cpp
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
class TNode {
private:
vector<TNode*> children;
bool end;
public:
TNode() : children(26, NULL) {
this->end = false;
}
void addChild(int child) {
this->children[child] = new TNode();
}
TNode* getChild(int child) {
return this->children[child];
}
void markEnd() {
this->end = true;
}
bool isEnd() {
return this->end;
}
};
class WordDictionary {
private:
TNode* root;
public:
/** Initialize your data structure here. */
WordDictionary() {
root = new TNode();
}
/** Adds a word into the data structure. */
void addWord(string word) {
TNode* curr = root, *child;
for (char x : word) {
child = curr->getChild(x-'a');
if (!child)
curr->addChild(x-'a');
curr = curr->getChild(x-'a');
}
curr->markEnd();
}
/** 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) {
TNode* curr = root;
return helper(0, curr, word);
}
bool helper(int currLetter, TNode* curr, string word) {
int i;
bool result;
TNode* child;
if (currLetter == word.length())
return curr->isEnd();
if (word[currLetter] != '.') {
child = curr->getChild(word[currLetter]-'a');
if (!child)
return false;
return helper(currLetter+1, child, word);
}
for (i = 0; i < 26; i++) {
child = curr->getChild(i);
if (child && helper(currLetter+1, child, word))
return true;
}
return false;
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/