-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path211.cpp
More file actions
61 lines (55 loc) · 1.61 KB
/
211.cpp
File metadata and controls
61 lines (55 loc) · 1.61 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
struct TrieNode{
struct TrieNode* child[26];
bool isEnd;
};
struct TrieNode* getNode(){
struct TrieNode* root = new TrieNode;
root->isEnd = false;
for(int i=0 ; i<26; i++)
root->child[i] = NULL;
return root;
}
class WordDictionary {
public:
/** Initialize your data structure here. */
TrieNode* root;
WordDictionary() {
root = getNode();
}
/** Adds a word into the data structure. */
void addWord(string key) {
struct TrieNode* curr = root;
for(int i=0; i<key.size(); i++){
int idx = key[i]-'a';
if(!curr->child[idx])
curr->child[idx] = getNode();
curr = curr->child[idx];
}
curr->isEnd = true;
}
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */
bool search(struct TrieNode* root, const char* key){
for(int i =0; (key[i] && root); i++){
if(key[i] != '.')
root = root->child[key[i]-'a'];
else{
TrieNode* tmp = root;
for(int j=0; j<26; j++){
root = tmp->child[j];
if(search(root,key+i+1))
return true;
}
}
}
return (root && root->isEnd);
}
bool search(string word) {
return search(root, word.c_str());
}
};
/**
* Your WordDictionary object will be instantiated and called as such:
* WordDictionary* obj = new WordDictionary();
* obj->addWord(word);
* bool param_2 = obj->search(word);
*/