-
Notifications
You must be signed in to change notification settings - Fork 0
/
Implement Trie
83 lines (66 loc) · 1.48 KB
/
Implement Trie
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
/*
Your Trie object will be instantiated and called as such:
Trie* obj = new Trie();
obj->insert(word);
bool check2 = obj->search(word);
bool check3 = obj->startsWith(prefix);
*/
class Node{
public:
Node *links[26];
bool flag = false;
Node(){}
bool containsKey(char ch){
return (links[ch-'a'] != NULL);
}
void put(char ch , Node *n){
links[ch-'a'] = n;
}
Node *get(char ch){
return links[ch-'a'];
}
void setend(){
flag = true;
}
bool isend(){
return flag;
}
};
class Trie {
public:
Node * root;
Trie() {
root = new Node();
}
void insert(string word) {
Node* n = root;
for(int i = 0 ; i<word.size() ; i++){
if(!n->containsKey(word[i])){
Node* temp = new Node();
n->put(word[i],temp);
}
n = n->get(word[i]);
}
n->setend();
}
bool search(string word) {
Node *n = root;
for(int i =0;i<word.size();i++){
if(!n->containsKey(word[i])){
return false;
}
n = n->get(word[i]);
}
return n->isend();
}
bool startsWith(string prefix) {
Node *n = root;
for(int i =0;i<prefix.size();i++){
if(!n->containsKey(prefix[i])){
return false;
}
n = n->get(prefix[i]);
}
return true;
}
};