-
Notifications
You must be signed in to change notification settings - Fork 0
/
!(IMP) Trie Implementation(Leetcode).cpp
83 lines (69 loc) · 1.8 KB
/
!(IMP) Trie Implementation(Leetcode).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
72
73
74
75
76
77
78
79
80
81
82
83
///////////////////////////////////////////////////////////////////////////////////
// using array
class Trie {
public:
Trie() {}
void insert(string word) {
Trie* node = this;
for (char ch : word) {
ch -= 'a';
if (!node->next[ch]) { node->next[ch] = new Trie(); }
node = node->next[ch];
}
node->isword = true;
}
bool search(string word) {
Trie* node = this;
for (char ch : word) {
ch -= 'a';
if (!node->next[ch]) { return false; }
node = node->next[ch];
}
return node->isword;
}
bool startsWith(string prefix) {
Trie* node = this;
for (char ch : prefix) {
ch -= 'a';
if (!node->next[ch]) { return false; }
node = node->next[ch];
}
return true;
}
private:
Trie* next[26] = {};
bool isword = false;
};
///////////////////////////////////////////////////////////////////////////
// using map
class Trie {
public:
Trie() {}
void insert(string word) {
Trie* node = this;
for (char ch : word) {
if (!node->next.count(ch)) { node->next[ch] = new Trie(); }
node = node->next[ch];
}
node->isword = true;
}
bool search(string word) {
Trie* node = this;
for (char ch : word) {
if (!node->next.count(ch)) { return false; }
node = node->next[ch];
}
return node->isword;
}
bool startsWith(string prefix) {
Trie* node = this;
for (char ch : prefix) {
if (!node->next.count(ch)) { return false; }
node = node->next[ch];
}
return true;
}
private:
map<char, Trie*> next = {};
bool isword = false;
};