-
Notifications
You must be signed in to change notification settings - Fork 95
/
Copy pathadd-and-search-word-data-structure-design.cpp
110 lines (91 loc) · 2.72 KB
/
add-and-search-word-data-structure-design.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
class WordDictionary {
private:
class TrieNode {
public:
TrieNode(char c = '\0') : val(c), complete_flag(false) {
for (int i = 0; i < 26; ++i) {
children[i] = NULL;
}
}
TrieNode* get_child(char c) {
int index = c - 'a';
if (index >= 0 && index < 26) {
return children[index];
}
return NULL;
}
TrieNode* add_child(char c) {
int index = c - 'a';
if (index < 0 || index >= 26) {
return NULL;
} else if (children[index] != NULL) {
return children[index];
}
children[index] = new TrieNode(c);
return children[index];
}
void set_complete_flag() {
complete_flag = true;
}
bool is_complete() {
return complete_flag;
}
char get_val() {
return val;
}
private:
char val;
bool complete_flag;
TrieNode* children[26];
};
TrieNode root;
public:
~WordDictionary() {
//TODO destroy trie
}
// Adds a word into the data structure.
void addWord(string word) {
TrieNode* cur = &root;
for (int i = 0; i < word.size() && cur != NULL; ++i) {
cur = cur->add_child(word[i]);
}
cur->set_complete_flag();
}
// 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) {
if (word.size() == 0) {
return true;
}
return search(word, 0, &root);
}
bool search(string& word, int index, TrieNode* node) {
if (node == NULL) {
return false;
}
if (word[index] != '.') {
TrieNode* cur = node->get_child(word[index]);
if (index == word.size() - 1) {
return cur != NULL && cur->is_complete();
} else {
return search(word, index + 1, cur);
}
} else {
bool find = false;
TrieNode* cur = NULL;
for (char c = 'a'; c <= 'z' && !find; ++c) {
cur = node->get_child(c);
if (index == word.size() - 1) {
find |= (cur != NULL && cur->is_complete());
} else {
find |= search(word, index + 1, cur);
}
}
return find;
}
}
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");