-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrie implementation with 2D array.cpp
More file actions
87 lines (66 loc) · 1.66 KB
/
Copy pathTrie implementation with 2D array.cpp
File metadata and controls
87 lines (66 loc) · 1.66 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
79
80
81
82
83
84
85
86
87
// Trie data structure implementation with 2D array.
// Language : C++11
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
const int MAXN = 10000 + 3;
const int ALPHABET = 26; // 'a' to 'z'
const int ROOT = 0;
int nxt[MAXN][ALPHABET];
int info[MAXN]; // It also can be a struct which binds several data.
int trieSize;
inline void reset_row(int v)
{
//for(int i = 0; i < ALPHABET; ++i) nxt[v][i] = 0;
fill(&nxt[v][0], &nxt[v][0]+ALPHABET, 0);
}
void trie_insert(string &str)
{
int v = ROOT;
for(auto &x : str) {
int &rf = nxt[v][x-'a'];
if(rf == 0) {
rf = ++trieSize;
reset_row(trieSize);
}
v = rf;
}
++info[v]; // Update info.
}
bool trie_search(string &str)
{
int v = ROOT;
for(auto &x : str) {
int &rf = nxt[v][x-'a'];
if(rf == 0) {
return false; // Full str isn't found.
}
v = rf;
}
return (info[v] > 0);
}
int main()
{
fill(info, info+MAXN, 0); // Reset info.
reset_row(ROOT); // Reset root row.
string keys[9] = {"a", "quick", "brown", "fox", "jumps", "over", "the", "lazy", "dog"};
string output[2] = {"Not Found", "Found"};
for(int i = 0; i < 9; ++i) trie_insert(keys[i]);
string qry = "a";
cout << output[trie_search(qry)] << '\n';
qry = "brown";
cout << output[trie_search(qry)] << '\n';
qry = "brwn";
cout << output[trie_search(qry)] << '\n';
qry = "white";
cout << output[trie_search(qry)] << '\n';
return 0;
}
/*
Output:
Found
Found
Not Found
Not Found
*/