-
Notifications
You must be signed in to change notification settings - Fork 1
/
Trie.h
53 lines (52 loc) · 972 Bytes
/
Trie.h
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
#include <unordered_map>
#include <cstring>
using namespace std;
#ifndef TRIE_H
#define TRIE_H
namespace trie {
class Node {
public:
unordered_map<char, Node*> mp;
char data;
bool isWord;
Node(char c) {
data = c;
isWord = false;
}
};
}
class Trie {
trie::Node* root;
public:
Trie() {
root = new trie::Node('\0');
}
void insert(string s) {
trie::Node* temp = root;
for(int i=0;s[i]!='\0';i++){
auto it = temp->mp.find(s[i]);
if(it==temp->mp.end()) {
trie::Node* newNode = new trie::Node(s[i]);
temp->mp[s[i]] = newNode;
temp = newNode ;
}
else {
temp = it->second;
}
}
temp->isWord = true;
}
bool isPresent(string s) {
trie::Node* temp = root;
for(int i=0;s[i]!='\0';i++){
auto it = temp->mp.find(s[i]);
if(it==temp->mp.end()) {
return false;
}
else
temp = it->second;
}
return temp->isWord;
}
};
#endif