forked from int32bit/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
trie.cpp
71 lines (70 loc) · 1.44 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
65
66
67
68
69
70
71
#include <cstdio>
#include <string>
#include <cstdlib>
#include <vector>
#include <iostream>
using namespace std;
class TrieNode {
public:
static const int SPACE_SIZE = 26;
TrieNode *children[SPACE_SIZE];
bool exist;
TrieNode() {
for (int i = 0; i < SPACE_SIZE; ++i) {
children[i] = nullptr;
}
exist = false;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
void insert(const string s) {
TrieNode *p = root;
for (char c : s) {
int index = c - 'a';
if (p->children[index] == nullptr) {
p->children[index] = new TrieNode();
}
p = p->children[index];
}
p->exist = true;
}
bool search(const string key) const {
TrieNode *p = root;
for (char c : key) {
int index = c - 'a';
if (p->children[index] == nullptr)
return false;
p = p->children[index];
}
return p->exist;
}
bool startsWith(const string prefix) const {
TrieNode *p = root;
for (char c : prefix) {
int index = c - 'a';
if (p->children[index] == nullptr)
return false;
p = p->children[index];
}
return true;
}
private:
TrieNode *root;
};
int main(int argc, char **argv)
{
Trie trie;
trie.insert("");
trie.insert("abcd");
cout << trie.search("abc") << endl;
cout << trie.search("abcd") << endl;;
cout << trie.startsWith("abc") << endl;
cout << trie.startsWith("abcd") << endl;
cout << trie.search("") << endl;
cout << trie.startsWith("") << endl;
return 0;
}