-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathimplement-trie-prefix-tree.cpp
95 lines (81 loc) · 1.48 KB
/
implement-trie-prefix-tree.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
struct TrieNode
{
TrieNode* links[26];
bool end = false;
TrieNode()
{
for (int i = 0; i < 26; i++)
{
links[i] = nullptr;
}
}
bool containKey(char ch)
{
return links[ch - 'a'] != nullptr;
}
void setKey(char ch)
{
links[ch - 'a'] = new TrieNode;
}
void setEnd()
{
end = true;
}
TrieNode* get(char ch)
{
return links[ch - 'a'];
}
bool isEnd()
{
return end;
}
};
class Trie {
private:
TrieNode* root;
TrieNode* node;
public:
Trie()
{
root = new TrieNode;
}
void insert(string word)
{
node = root;
for (char ch: word)
{
if (node->containKey(ch) != true)
{
node->setKey(ch);
}
node = node->get(ch);
}
node->setEnd();
}
bool search(string word)
{
node = root;
for (char ch: word)
{
if (node->containKey(ch) != true)
{
return false;
}
node = node->get(ch);
}
return node->isEnd();
}
bool startsWith(string word)
{
node = root;
for (char ch: word)
{
if (node->containKey(ch) != true)
{
return false;
}
node = node->get(ch);
}
return true;
}
};