@@ -26,12 +26,13 @@ namespace my {
26
26
}
27
27
28
28
// Insert a word into the Trie
29
- void Trie::insert (const std::string& word)
29
+ void Trie::insert (std::string_view word)
30
30
{
31
31
TrieNode* node = m_root;
32
+
32
33
for (char ch : word)
33
34
{
34
- if (!node->children .count (ch))
35
+ if (!node->children .contains (ch))
35
36
{
36
37
node->children [ch] = new TrieNode ();
37
38
}
@@ -41,20 +42,20 @@ namespace my {
41
42
}
42
43
43
44
// Search for a word in the Trie
44
- bool Trie::search (const std::string& word) const
45
+ bool Trie::search (std::string_view word) const
45
46
{
46
47
TrieNode* node = find_node (word);
47
48
return node != nullptr && node->is_end_of_word ;
48
49
}
49
50
50
51
// Check if any word starts with the given prefix
51
- bool Trie::starts_with (const std::string& prefix) const
52
+ bool Trie::starts_with (std::string_view prefix) const
52
53
{
53
54
return find_node (prefix) != nullptr ;
54
55
}
55
56
56
57
// Remove a word from the Trie
57
- void Trie::remove (const std::string& word)
58
+ void Trie::remove (std::string_view word)
58
59
{
59
60
remove_helper (m_root, word, 0 );
60
61
}
@@ -71,7 +72,9 @@ namespace my {
71
72
void Trie::destroy_node (TrieNode* node)
72
73
{
73
74
if (!node)
75
+ {
74
76
return ;
77
+ }
75
78
76
79
for (auto & [ch, child] : node->children )
77
80
{
@@ -81,7 +84,7 @@ namespace my {
81
84
}
82
85
83
86
// Helper function to find the node corresponding to a given prefix
84
- Trie::TrieNode* Trie::find_node (const std::string& prefix) const
87
+ Trie::TrieNode* Trie::find_node (std::string_view prefix) const
85
88
{
86
89
TrieNode* node = m_root;
87
90
for (char ch : prefix)
@@ -109,21 +112,26 @@ namespace my {
109
112
}
110
113
111
114
// Helper function to remove a word from the Trie
112
- bool Trie::remove_helper (TrieNode* node, const std::string& word, size_t depth)
115
+ bool Trie::remove_helper (TrieNode* node, std::string_view word, size_t depth)
113
116
{
114
117
if (!node)
118
+ {
115
119
return false ;
120
+ }
116
121
117
122
if (depth == word.size ())
118
123
{
119
124
if (!node->is_end_of_word )
125
+ {
120
126
return false ;
127
+ }
128
+
121
129
node->is_end_of_word = false ;
122
130
return node->children .empty ();
123
131
}
124
132
125
133
char ch = word[depth];
126
- if (!node->children .count (ch) || !remove_helper (node->children [ch], word, depth + 1 ))
134
+ if (!node->children .contains (ch) || !remove_helper (node->children [ch], word, ++depth ))
127
135
{
128
136
return false ;
129
137
}
0 commit comments