forked from abbh07/DataStructure-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Trie.cpp
73 lines (66 loc) · 1.13 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
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
using namespace std;
struct Trie
{
map<char,Trie*> children;
bool end_of_word;
};
Trie *root = new Trie();
void insert(string word)
{
Trie *current = root;
for(int i=0;i<word.size();i++)
{
char ch = word[i];
int val = current->children.count(ch);//Returns 1 if ch is found else 0
Trie *node;
if(val == 0)
{
node = new Trie();
node->end_of_word = false;
current->children.insert(make_pair(ch,node));
}
else
{
node = current->children[ch];
}
current = node;
}
current->end_of_word = true;
}
//Whole word search
bool search(string word)
{
Trie *current = root;
for(int i=0;i<word.size();i++)
{
char ch = word[i];
int val = current->children.count(ch);
Trie *node;
if(val == 0)
{
return false;
}
else
{
node = current->children[ch];
}
current = node;
}
return current->end_of_word;
}
int main()
{
root->end_of_word = false;
insert("abcd");
insert("abcde");
insert("xyz");
cout<<search("abcd")<<endl;
cout<<search("abcde")<<endl;
cout<<search("abc")<<endl;
cout<<search("xyz")<<endl;
return 0;
}