-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
68 lines (61 loc) · 1.39 KB
/
Solution.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
#include <algorithm>
#include <climits>
#include <functional>
#include <iostream>
#include <queue>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
class TrieNode {
public:
bool isWord;
vector<TrieNode*> children;
TrieNode() : isWord(false), children(26, nullptr) {}
};
class Trie {
private:
TrieNode* root;
public:
Trie() : root(new TrieNode()) {};
void insert(string word) {
TrieNode* iter = root;
for (auto const& c : word) {
if (!iter->children[c - 'a']) {
iter->children[c - 'a'] = new TrieNode();
}
iter = iter->children[c - 'a'];
}
iter->isWord = true;
}
bool search(string word) {
TrieNode* iter = root;
for (auto const& c : word) {
if (!iter->children[c - 'a']) {
return false;
}
iter = iter->children[c - 'a'];
}
return iter->isWord;
}
bool startsWith(string prefix) {
TrieNode* iter = root;
for (auto const& c : prefix) {
if (!iter->children[c - 'a']) {
return false;
}
iter = iter->children[c - 'a'];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
* word and prefix consists of only lowercase English letters
*/