-
Notifications
You must be signed in to change notification settings - Fork 208
/
Copy pathTrie.cpp
102 lines (84 loc) · 2.45 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
#include<bits/stdc++.h>
using namespace std;
class TrieNode{
public:
unordered_map<char,TrieNode*> umap;
bool endofword = false;
};
class Trie {
public:
TrieNode* root;
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode* node = root;
int i=0;
TrieNode* new_node;
while(i<word.length()){
auto itr = (node->umap).find(word[i]);
if(itr == (node->umap).end()){
new_node = new TrieNode();
if(i==word.length()-1){
new_node->endofword = true;
}
(node->umap).insert({word[i],new_node});
node = new_node;
}else{
node = itr->second;
if(i==word.length()-1){
node->endofword = true;
}
}
i++;
}
}
bool search(string word) {
TrieNode* node = root;
int i = 0;
while(i<word.length()){
auto itr = (node->umap).find(word[i]);
if(itr != (node->umap).end()){
node = itr->second;
i++;
}else{
return false;
}
}
if(node->endofword){
return true;
}
return false;
}
bool startsWith(string prefix) {
TrieNode* node = root;
int i = 0;
while(i<prefix.length()){
auto itr = (node->umap).find(prefix[i]);
if(itr != (node->umap).end()){
node = itr->second;
i++;
}else{
return false;
}
}
return true;
}
};
int main(){
vector<string> arr = {"apple","app","aps","lmn"};
vector<string> prefixs = {"app","lmn","ln","al"};
vector<string> word_search = {"apple","apps"};
Trie* obj = new Trie();
for(int i=0;i<arr.size();i++)
obj->insert(arr[i]);
for(int i=0;i<word_search.size();i++){
bool param_2 = obj->search(word_search[i]);
cout<<word_search[i]<<" : "<<param_2<<endl;
}
for(int i=0;i<prefixs.size();i++){
bool param_3 = obj->startsWith(prefixs[i]);
cout<<prefixs[i]<<" : "<<param_3<<endl;
}
return 0;
}