-
Notifications
You must be signed in to change notification settings - Fork 111
/
add-and-search-word-data-structure-design.cc
52 lines (47 loc) · 1.27 KB
/
add-and-search-word-data-structure-design.cc
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
// Add and Search Word - Data structure design
class WordDictionary {
public:
class TrieNode {
public:
// Initialize your data structure here.
bool has;
TrieNode *c[26];
TrieNode() : has(false) {
fill_n(c, 26, nullptr);
}
} *root;
WordDictionary() : root(new TrieNode) {}
// Adds a word into the data structure.
void addWord(string word) {
auto x = root;
for (auto c: word) {
if (! x->c[c-'a'])
x->c[c-'a'] = new TrieNode;
x = x->c[c-'a'];
}
x->has = true;
}
// 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 search(word, 0, root);
}
bool search(const string &word, string::size_type i, TrieNode *x) {
for (; i < word.size(); i++) {
if (word[i] == '.') {
for (int j = 0; j < 26; j++)
if (x->c[j] && search(word, i+1, x->c[j]))
return true;
return false;
}
if (! x->c[word[i]-'a'])
return false;
x = x->c[word[i]-'a'];
}
return x->has;
}
};
// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary;
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");