-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathtrie.cpp
64 lines (59 loc) · 1.83 KB
/
trie.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
// trie class implementation.
#include <bits/stdc++.h>
using namespace std;
class Trie {
public:
Trie* child[26]; // for 26 diff childs.
bool end;
Trie() {
for (int i = 0; i < 26; i++) child[i] = nullptr;
end = false;
}
void insert(string word) {
if (!word.size()) return;
Trie* current = child[word[0] - 'a'];
if (current == nullptr) current = new Trie();
child[word[0] - 'a'] = current;
for (int i = 1; i < word.size(); i++) {
if (current == nullptr) current = new Trie();
if (!current->child[word[i] - 'a']) {
current->child[word[i] - 'a'] = new Trie();
}
current = current->child[word[i] - 'a'];
}
current->end = true;
}
bool search(string word) {
if (!word.size()) return true;
Trie* current = child[word[0] - 'a'];
if (current == nullptr) return false;
for (int i = 1; i < word.size(); i++) {
if (!current->child[word[i] - 'a']) {
return false;
}
current = current->child[word[i] - 'a'];
}
return current->end;
}
bool startsWith(string word) {
if (!word.size()) return true;
Trie* current = child[word[0] - 'a'];
if (current == nullptr) return false;
for (int i = 1; i < word.size(); i++) {
if (!current->child[word[i] - 'a']) {
return false;
}
current = current->child[word[i] - 'a'];
}
return true;
}
};
int main() {
Trie* trie = new Trie();
trie->insert("apple");
trie->search("apple"); // return True
trie->search("app"); // return False
trie->startsWith("app"); // return True
trie->insert("app");
trie->search("app"); // return True
}