Skip to content

Commit 4653a73

Browse files
author
Vip2016-0
committed
Implement_Trie
1 parent fec7629 commit 4653a73

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed

CPP/Tries/implementTrie.cpp

+55
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
class Node {
2+
public:
3+
char c;
4+
Node* child[26];
5+
bool isWord;
6+
7+
Node(char c) {
8+
this -> c = c;
9+
isWord = false;
10+
11+
for(int i = 0 ; i < 26 ; i++)
12+
child[i] = NULL;
13+
}
14+
};
15+
16+
class Trie {
17+
Node* root;
18+
Node* getNode(string &s){
19+
Node* curr = root;
20+
for(auto &ch:s){
21+
if(curr -> child[ch - 97] == NULL)
22+
return NULL;
23+
curr = curr -> child[ch - 97];
24+
}
25+
26+
return curr;
27+
}
28+
public:
29+
Trie() {
30+
root = new Node('\0');
31+
}
32+
33+
void insert(string word) {
34+
Node* curr = root;
35+
36+
for(auto &ch:word){
37+
if(curr -> child[ch - 97] == NULL)
38+
curr -> child[ch - 97] = new Node(ch);
39+
curr = curr -> child[ch - 97];
40+
}
41+
42+
curr -> isWord = true;
43+
}
44+
45+
bool search(string word) {
46+
Node* reqNode = getNode(word);
47+
48+
return reqNode && reqNode -> isWord;
49+
}
50+
51+
bool startsWith(string prefix) {
52+
return getNode(prefix) != NULL;
53+
}
54+
};
55+

0 commit comments

Comments
 (0)