-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtrie.cpp
executable file
·52 lines (47 loc) · 1.3 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
#include <vector>
#include <string>
#include "trie.h"
using namespace std;
TrieNode::TrieNode() {
this->isEnd = false;
this->children = vector<TrieNode*>(256, nullptr);
}
Trie::Trie() {
root = new TrieNode();
}
void Trie::insert(string const& word) {
TrieNode* curr = root;
for (auto c : word){
if (curr->children[c] == nullptr){
curr->children[c] = new TrieNode();
}
curr = curr->children[c];
}
curr->isEnd = true;
}
bool Trie::search(string const& word) {
TrieNode* curr = root;
for (auto c : word){
if (curr->children[c] == nullptr) return false;
curr = curr->children[c];
}
return curr != nullptr && curr->isEnd;
}
bool Trie::startsWith(string const& prefix) {
TrieNode* curr = root;
for (auto c : prefix){
if (curr->children[c] == nullptr) return false;
curr = curr->children[c];
}
return curr != nullptr;
}
bool Trie::hasPrefix(string const& prefix, int& position) {
TrieNode* curr = root;
for (int i = 0; i < prefix.size(); i++) {
if (curr->isEnd) return true;
if (curr->children[prefix[i]] == nullptr) return false;
curr = curr->children[prefix[i]];
position = i;
}
return curr != nullptr && curr->isEnd;
}