-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathAddandSearchWord.cpp
More file actions
72 lines (62 loc) · 1.41 KB
/
AddandSearchWord.cpp
File metadata and controls
72 lines (62 loc) · 1.41 KB
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
class TrieNode {
public:
char c;
map<char, TrieNode*> child;
TrieNode(char character) {
c = character;
}
};
class Trie {
public:
TrieNode* root;
Trie() {
root = new TrieNode('\0');
end = new TrieNode('\0');
}
// Inserts a word into the trie.
void insert(string word) {
int i = 0;
TrieNode *tmp, *child;
for (i = 0, tmp = root; word[i]; i++){
child = tmp->child[word[i]];
if (!child){
child = new TrieNode(word[i]);
tmp->child[word[i]] = child;
}
tmp = child;
}
tmp->child[0] = end;
}
// Returns if the word is in the trie.
bool search(string word, TrieNode* current, int i) {
TrieNode* child = current->child[word[i]];
if (!word[i]){
if (child == end) return true;
return false;
}
if (word[i] != '.'){
if (child) return search(word, child, i + 1);
return false;
}
bool flag = false;
for (map<char, TrieNode*>::iterator it = current->child.begin(); it != current->child.end(); it++)
if (it->second) flag |= search(word, it->second, i + 1);
return flag;
}
private:
TrieNode* end;
};
class WordDictionary {
public:
// Adds a word into the data structure.
void addWord(string word) {
dictionary.insert(word);
}
// 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) {
return dictionary.search(word, dictionary.root, 0);
}
private:
Trie dictionary;
};