-
Notifications
You must be signed in to change notification settings - Fork 205
/
trie.cpp
67 lines (64 loc) · 1.54 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
#include<bits/stdc++.h>
using namespace std;
struct trie{
struct trie* child[26];
bool is_end;
trie(){
memset(child,0,sizeof(child));
is_end=false;
}
};
struct trie* root;
//inserts a word to the trie
void insert(string s){
struct trie* temp=root;
//traverses over each character
//if the character already exists then it simply iterates over
//otherwise creates a new node and inserts the character
for(char c: s){
if(!temp->child[c-'a'])
temp->child[c-'a']=new trie;
temp=temp->child[c-'a'];
}
//sets the last letter's boolean value to true
temp->is_end=true;
}
//returns true if the word exists, false otherwise
bool check(string s){
struct trie* temp=root;
//iterates over the character of the word
for(char c: s){
//if at any point the char of the word being check is not found it return false
if(!temp->child[c-'a'])
return false;
temp=temp->child[c-'a'];
}
//returns the last letters boolean value
return temp->is_end;
}
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
root=new trie;
int n;
cout << "Input the number of words in the List" << endl;
cin >> n;
string word;
cout<<"Enter the words"<<endl;
//words that are being inserted to trie.
for(int i=0; i<n; i++){
cin >> word ;
insert(word);
}
cout << "Enter the number of words you want to check exist in the List" << endl;
int m;
cin >> m;
//the words to be checked
for(int i=0; i<m; i++){
cin >> word ;
if(check(word))
cout<< "This word exist in the list" <<endl;
else
cout<< "This word does not exist in the list"<<endl;
}
}