-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path208_implement_trie.cpp
More file actions
90 lines (76 loc) · 2.46 KB
/
208_implement_trie.cpp
File metadata and controls
90 lines (76 loc) · 2.46 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
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
89
90
/*
LeetCode 208 - Implement Trie (Prefix Tree)
Difficulty: Medium
Problem:
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently
store and retrieve keys in a dataset of strings. Implement the Trie class:
- Trie() Initializes the trie object.
- void insert(String word) Inserts the string word into the trie.
- boolean search(String word) Returns true if word is in the trie, false otherwise.
- boolean startsWith(String prefix) Returns true if there is a previously inserted string
that has the prefix prefix, and false otherwise.
Example 1:
Input: ["Trie","insert","search","search","startsWith","insert","search"]
[[],["apple"],["apple"],["app"],["app"],["app"],["app"]]
Output: [null,null,true,false,true,null,true]
Time Complexity: O(m) for all operations, where m is key length
Space Complexity: O(m) for insert, O(1) for search/startsWith
*/
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
class TrieNode {
public:
unordered_map<char, TrieNode*> children;
bool is_end;
TrieNode() : is_end(false) {}
};
class Trie {
private:
TrieNode* root;
public:
Trie() {
root = new TrieNode();
}
void insert(string word) {
TrieNode* node = root;
for (char c : word) {
if (node->children.find(c) == node->children.end()) {
node->children[c] = new TrieNode();
}
node = node->children[c];
}
node->is_end = true;
}
bool search(string word) {
TrieNode* node = root;
for (char c : word) {
if (node->children.find(c) == node->children.end()) {
return false;
}
node = node->children[c];
}
return node->is_end;
}
bool startsWith(string prefix) {
TrieNode* node = root;
for (char c : prefix) {
if (node->children.find(c) == node->children.end()) {
return false;
}
node = node->children[c];
}
return true;
}
};
int main() {
Trie trie;
trie.insert("apple");
cout << (trie.search("apple") ? "true" : "false") << endl; // true
cout << (trie.search("app") ? "true" : "false") << endl; // false
cout << (trie.startsWith("app") ? "true" : "false") << endl; // true
trie.insert("app");
cout << (trie.search("app") ? "true" : "false") << endl; // true
return 0;
}