-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtrie.cpp
More file actions
60 lines (50 loc) · 1.14 KB
/
trie.cpp
File metadata and controls
60 lines (50 loc) · 1.14 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
#include<bits/stdc++.h>
using namespace std;
class Node {
public:
static const int SIZE = 1 << 8;
Node * nxt[SIZE];
bool isWord;
Node(){
memset(nxt, 0, sizeof nxt);
isWord = false;
}
};
class Trie {
private:
Node * root;
public:
Trie() : root(new Node()) {
}
void insert(const string & word) {
Node * cur = root;
for(auto c: word) {
if(!cur->nxt[c]) cur->nxt[c] = new Node();
cur = cur->nxt[c];
}
cur->isWord = true;
}
bool search(string word) {
return find(word, false);
}
bool startsWith(string prefix) {
return find(prefix, true);
}
bool find(const string & word, bool prefix) {
Node * cur = root;
for(auto c: word) {
if(!cur->nxt[c]) return false;
cur = cur->nxt[c];
}
return prefix || (cur && cur->isWord);
}
};
/**
* 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);
*/
int main() {
}