-
Notifications
You must be signed in to change notification settings - Fork 1
/
208-Implement-Trie.cpp
58 lines (50 loc) · 1.35 KB
/
208-Implement-Trie.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
class Trie {
public:
/** Initialize your data structure here. */
struct TrieNode{
struct TrieNode* child[26];
bool isleaf;
};
TrieNode* node;
Trie() {
node = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* curnode = node;
for(char c : word){
if(curnode->child[c-'a'] == NULL){
curnode->child[c-'a'] = new TrieNode();
}
curnode = curnode->child[c-'a'];
}
curnode->isleaf = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode* curnode = node;
for(char c : word){
if(curnode->child[c-'a'] == NULL){
return false;
}
curnode = curnode->child[c-'a'];
}
if(curnode->isleaf) {
return true;
}
else{
return false;
}
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode* curnode = node;
for(char c : prefix){
if(curnode->child[c-'a'] == NULL){
return false;
}
curnode = curnode->child[c-'a'];
}
return true;
}
};