-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplement-trie-prefix-tree(AC).cpp
More file actions
106 lines (88 loc) · 1.94 KB
/
Copy pathimplement-trie-prefix-tree(AC).cpp
File metadata and controls
106 lines (88 loc) · 1.94 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// 2CE, 1RE, 1AC
// Such a problem is not about algorithm, it is about being bug-free.
// So, be sure to read your code before submitting.
// It is guaranteed that all words contain only lower-case letters.
class TrieNode {
public:
static const int N = 26;
bool is_word;
// Initialize your data structure here.
TrieNode() {
// typing error here
// child = new TrieNode[N];
child = new TrieNode*[N];
for (int i = 0; i < N; ++i) {
// typing error here.
// child[N] = NULL;
child[i] = NULL;
}
is_word = false;
}
~TrieNode() {
delete[] child;
}
TrieNode **child;
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
int n = word.length();
if (n == 0) {
return;
}
TrieNode *p1;
p1 = root;
for (int i = 0; i < n; ++i) {
if (p1->child[word[i] - 'a'] == NULL) {
p1->child[word[i] - 'a'] = new TrieNode();
}
p1 = p1->child[word[i] - 'a'];
}
p1->is_word = true;
}
// Returns if the word is in the trie.
bool search(string word) {
int n = word.length();
if (n == 0) {
return false;
}
TrieNode *p1;
p1 = root;
for (int i = 0; i < n; ++i) {
if (p1->child[word[i] - 'a'] == NULL) {
return false;
}
p1 = p1->child[word[i] - 'a'];
}
return p1->is_word;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
// typing error here
// int n = word.length();
int n = prefix.length();
if (n == 0) {
return true;
}
TrieNode *p1;
p1 = root;
for (int i = 0; i < n; ++i) {
if (p1->child[prefix[i] - 'a'] == NULL) {
return false;
}
p1 = p1->child[prefix[i] - 'a'];
}
return p1 != NULL;
}
private:
TrieNode* root;
};
// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");