-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode_208_Implement_Trie.cpp
More file actions
59 lines (53 loc) · 1.32 KB
/
Copy pathLeetCode_208_Implement_Trie.cpp
File metadata and controls
59 lines (53 loc) · 1.32 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
/*
208. Implement Trie ( Prefix Tree )
Implement a trie with insert, search, and startsWith methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
Note:
You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
*/
class Trie {
unordered_map<char, Trie*> children;
bool wordEndHere;
public:
Trie() {
wordEndHere = false;
}
void insert( string word ) {
Trie *curr = this;
for( auto s : word ) {
if( curr->children.find(s) == curr->children.end() ) {
curr->children[s] = new Trie();
}
curr = curr->children[s];
}
curr->wordEndHere = true;
}
bool search( string word ) {
Trie *curr = this;
for( auto s : word ) {
if( curr->children.find(s) == curr->children.end() ) {
return false;
}
curr = curr->children[s];
}
return curr->wordEndHere;
}
bool startsWith( string prefix ) {
Trie *curr = this;
for( auto s : prefix ) {
if( curr->children.find(s) == curr->children.end() ) {
return false;
}
curr = curr->children[s];
}
return true;
}
};