-
Notifications
You must be signed in to change notification settings - Fork 368
/
Trie.cpp
107 lines (85 loc) · 2.41 KB
/
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
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
// C++ implementation of search and insert operations on Trie
#include <bits/stdc++.h>
using namespace std;
// TrieNode Class
class TrieNode
{
public:
TrieNode *children[26];
// isEndOfWord is true if the node represents end of a word
bool isEndOfWord;
// Construtor
TrieNode() {
// Initializing the children array with NULL
for(int i = 0 ; i < 26; i++) {
children[i] = NULL;
}
// Initializing isEndOfWord with false
isEndOfWord = false;
}
};
// Trie class
class Trie
{
private:
TrieNode *root;
public:
// Constructor
Trie() {
// Creeating a new TrieNode
root = new TrieNode();
}
// If not present, inserts key into trie
// If the key is prefix of trie node, just marks leaf node
void insert(string word)
{
TrieNode *curr = root;
for (int i = 0; i < word.length(); i++)
{
int index = word[i] - 'a';
if (!curr -> children[index]) {
curr -> children[index] = new TrieNode();
}
curr = curr -> children[index];
}
// mark last node as leaf
curr -> isEndOfWord = true;
}
// Returns true if key presents in trie, else false
bool search(string key)
{
TrieNode *curr = root;
for (int i = 0; i < key.length(); i++)
{
int index = key[i] - 'a';
if (!curr -> children[index]) {
return false;
}
curr = curr -> children[index];
}
return curr -> isEndOfWord;
}
};
int main()
{
int n;
cin>>n;
string keys[n];
// Input keys (use only 'a' through 'z' and lower case)
for(int i = 0; i < n; i++) {
cin>>keys[i];
}
Trie *t = new Trie();
// Construct trie
for (int i = 0; i < n; i++) {
t -> insert(keys[i]);
}
// Output based on the result
char output[][32] = {"Not present in trie", "Present in trie"};
// Search for different keys
cout<<"the"<<" -> "<<output[t -> search("the")]<<endl;
cout<<"these"<<" -> "<<output[t -> search("these")]<<endl;
cout<<"their"<<" -> "<<output[t -> search("their")]<<endl;
cout<<"thaw"<<" -> "<<output[t -> search("thaw")]<<endl;
return 0;
}