-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path211. Add and Search Word - Data structure design.cpp
More file actions
64 lines (63 loc) · 1.4 KB
/
211. Add and Search Word - Data structure design.cpp
File metadata and controls
64 lines (63 loc) · 1.4 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
class WordDictionary {
public:
struct trie{
struct trie *word[26];
bool isend[26];
bool next;
trie(){
for (int i = 0; i != 26; ++i){
word[i] = NULL;
isend[i] = false;
}
next = false;
}
trie(char c){
for (int i = 0; i != 26; ++i){
isend[i] = false;
word[i] = NULL;
}
word[c - 'a'] = new struct trie();
next = true;
}
};
struct trie t;
// Adds a word into the data structure.
void addWord(string word) {
struct trie * ptr = &t,*pre = ptr;
for (int i = 0; word[i]; ++i){
if (ptr->word[word[i] - 'a'] == NULL){
ptr->next = true;
ptr->word[word[i] - 'a'] = new trie();
}
if (word[i + 1] == 0){
ptr->isend[word[i] - 'a'] = true;
}
ptr = ptr->word[word[i] - 'a'];
}
}
// 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 help(word, &t,0,false);
}
bool help(string &word, struct trie *root,int pos,bool isend){
if (word[pos] == 0)return isend;
if (word[pos] == '.'){
bool flag = false;
for (int i = 0; i != 26; ++i){
if (root->word[i]){
flag = flag || help(word, root->word[i], pos + 1,root->isend[i]);
}
}
return flag;
}
else{
if (root->word[word[pos] - 'a'] == NULL){
return false;
}
else{
return help(word, root->word[word[pos] - 'a'], pos + 1,root->isend[word[pos]-'a']);
}
}
}
};