-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0208_Trie.cc
95 lines (87 loc) · 1.48 KB
/
Problem_0208_Trie.cc
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
#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;
class Trie
{
public:
Trie() { root = new Node(); }
void insert(string word)
{
if (word.length() == 0)
{
return;
}
Node *cur = root;
cur->pass++;
for (char &c : word)
{
int index = c;
if (!cur->nexts.count(index))
{
cur->nexts.emplace(index, new Node());
}
cur = cur->nexts.at(index);
cur->pass++;
}
cur->end++;
}
bool search(string word)
{
if (word.length() == 0)
{
return true;
}
Node *cur = root;
for (char &c : word)
{
int index = c;
if (!cur->nexts.count(index))
{
return false;
}
cur = cur->nexts.at(index);
}
return cur->end > 0;
}
bool startsWith(string prefix)
{
if (prefix.length() == 0)
{
return true;
}
Node *cur = root;
for (char &c : prefix)
{
int index = c;
if (!cur->nexts.count(index))
{
return false;
}
cur = cur->nexts.at(index);
}
return cur->pass > 0;
}
private:
class Node
{
public:
int pass;
int end;
unordered_map<int, Node *> nexts;
Node()
{
pass = 0;
end = 0;
}
};
Node *root;
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/