Repository navigation
Expand file tree
/
Copy pathsolution.cpp
More file actions
59 lines (50 loc) · 1.41 KB
/
Copy pathsolution.cpp
File metadata and controls
59 lines (50 loc) · 1.41 KB
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
// Stepsort · Implement Trie (Prefix Tree)
// Category: LeetCode Patterns
// Animated walkthrough: https://stepsort.prakashraj.me/algorithm/implement-trie
#include <bits/stdc++.h>
using namespace std;
struct TrieNode {
TrieNode* children[26];
bool isEnd;
TrieNode() : children{}, isEnd(false) {}
};
class Trie {
public:
Trie() : root(new TrieNode()) {}
void insert(const string& word) {
TrieNode* node = root;
for (char ch : word) {
int idx = ch - 'a';
if (!node->children[idx]) node->children[idx] = new TrieNode();
node = node->children[idx];
}
node->isEnd = true;
}
bool search(const string& word) {
TrieNode* node = find(word);
return node && node->isEnd;
}
bool startsWith(const string& prefix) {
return find(prefix) != nullptr;
}
private:
TrieNode* root;
TrieNode* find(const string& s) {
TrieNode* node = root;
for (char ch : s) {
node = node->children[ch - 'a'];
if (!node) return nullptr;
}
return node;
}
};
int main() {
Trie trie;
trie.insert("apple");
cout << boolalpha << trie.search("apple") << endl;
cout << boolalpha << trie.search("app") << endl;
cout << boolalpha << trie.startsWith("app") << endl;
trie.insert("app");
cout << boolalpha << trie.search("app") << endl;
return 0;
}