-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathTrie.cpp
66 lines (57 loc) · 1.47 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
/*
* Author : Fakhra Najm <fnajm09@gmail.com>
* Topic : Implementation of Trie Datastructure
* A Trie is a special data structure used to store strings that can be visualized like a graph.
* They are used to represent the “Retrieval” of data and thus the name Trie.
* Application - String Processing
- Search Engine
- Gnome analysis
- Data Analytics
*/
#include<bits/stdc++.h>
using namespace std;
class Trie{
map<char, Trie *> next = {};
bool isWord = false;
public:
void update(string word){
Trie *node = this;
for(auto letter : word){
if(!node -> next[letter]) node -> next[letter] = new Trie();
node = node -> next[letter];
}
node -> isWord = true;
}
bool read(string word){
Trie *node = this;
for(auto letter : word){
if(!node -> next[letter]) return false;
node = node -> next[letter];
}
return node -> isWord;
}
bool isPrefix(string prefix){
Trie *node = this;
for(auto letter : prefix){
if(!node -> next[letter]) return false;
node = node -> next[letter];
}
return true;
}
};
int main(){
Trie trie;
string word, prefix, search;
cout << "Enter String : " << endl;
cin >> word;
trie.update(word);
cout << "Enter Prefix : " << endl;
cin >> prefix;
if(trie.isPrefix(prefix)) cout << "Prefix found" << endl;
else cout << "Prefix Not Found " << endl;
cout << "Enter word to search : " << endl;
cin >> search;
if(trie.read(search)) cout << "Word found" << endl;
else cout << "Word Not Found " << endl;
return 0;
}