-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path00208-implement_trie_prefix_tree.cpp
88 lines (67 loc) · 1.87 KB
/
00208-implement_trie_prefix_tree.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
84
85
86
87
88
// 208: Implement Trie Prefix Tree
// https://leetcode.com/problems/implement-trie-prefix-tree
#include <iostream>
#include <string>
using namespace std;
class TrieNode {
public:
TrieNode* children[26];
bool isWord;
TrieNode() {
for (int i=0; i<26; i++) children[i] = NULL;
isWord = false;
}
};
class Trie {
private:
TrieNode* root;
public:
Trie() {
this->root = new TrieNode();
}
void insert(string word) {
TrieNode* node = root;
int current = 0;
for (int i=0; i<word.size(); i++) {
current = word[i] - 'a';
if (node->children[current] == NULL)
node->children[current] = new TrieNode();
node = node->children[current];
}
node->isWord = true;
}
bool search(string word) {
TrieNode* node = root;
int current = 0;
for (int i=0; i<word.size(); i++) {
current = word[i] - 'a';
if (node->children[current] == NULL)
return false;
node = node->children[current];
}
return node->isWord;
}
bool startsWith(string prefix) {
TrieNode* node = root;
int current = 0;
for (int i=0; i<prefix.size(); i++) {
current = prefix[i] - 'a';
if (node->children[current] == NULL) {
return false;
}
node = node->children[current];
}
return true;
}
};
int main() {
Trie* trie = new Trie();
// OPERATION
trie->insert("apple");
cout << (trie->search("apple") ? "true" : "false") << endl;
cout << (trie->search("app") ? "true" : "false") << endl;
cout << (trie->startsWith("app") ? "true" : "false") << endl;
trie->insert("app");
cout << (trie->search("app") ? "true" : "false") << endl;
return 0;
}