-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path123. Design add and search word.cpp
More file actions
48 lines (41 loc) · 1.27 KB
/
123. Design add and search word.cpp
File metadata and controls
48 lines (41 loc) · 1.27 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
class WordDictionary {
public:
struct Trie {
char c;
bool isWord=false;
struct Trie* children[26];
};
Trie *node;
WordDictionary() {
node=new Trie();
}
void addWord(string word) {
int current_word_length=word.length();
Trie *curr=node;
for(int i=0; i<current_word_length; i++) {
if(curr->children[word[i]-'a']== NULL) curr->children[word[i]-'a']= new Trie();
curr=curr->children[word[i]-'a'];
}
curr->isWord=true;
}
bool search(string word,Trie* tempRoot=NULL) {
Trie * curr;
if(!tempRoot) curr=node;
else curr=tempRoot;
int current_word_length=word.length();
for(int i=0; i<current_word_length; i++) {
char c=word[i];
if(c=='.') {
for(int j=0; j<26; j++) {
if(curr->children[j]!=NULL&&search(word.substr(i+1, word.size()-i),curr->children[j])) return true;
}
return false;
} else{
if(curr->children[c-'a']==NULL)
return false;
curr=curr->children[c-'a'];
}
}
return curr->isWord;
}
};