-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtries.cpp
More file actions
78 lines (67 loc) · 1.03 KB
/
tries.cpp
File metadata and controls
78 lines (67 loc) · 1.03 KB
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
// Tries
#include <iostream>
#include <unordered_map>
using namespace std;
class node{
public:
char ch;
bool isTerminal;
unordered_map<char,node*> h;
node(char c){
ch = c;
isTerminal = false;
}
};
class Trie{
node* root;
public:
Trie(){
root = new node('\0');
}
void addWord(char* word){
node* temp =root;
for(int i=0;word[i]!='\0';i++){
char ch = word[i];
if(temp->h.count(ch)==1){
temp=temp->h[ch];
}
else{
temp->h[ch] = new node(ch);
temp=temp->h[ch];
}
}
temp->isTerminal = true;
}
bool searchWord(char *word){
node* temp = root;
for(int i=0;word[i]!='\0';i++){
char ch=word[i];
if(temp->h.count(ch)==0){
return false;
}
else{
temp=temp->h[ch];
}
}
return temp->isTerminal;
}
};
int main(){
Trie t;
t.addWord("Hello");
t.addWord("Hell");
t.addWord("Code");
t.addWord("Coding");
t.addWord("Coder");
char ch[100];
while(1){
cin>>ch;
if(t.searchWord(ch)){
cout<<"Found"<<endl;
}
else{
cout<<"Not Found"<<endl;
}
}
return 0;
}