49 lines
793 B
C++
49 lines
793 B
C++
class Trie
|
|
{
|
|
private:
|
|
vector<Trie*> m_children;
|
|
bool is_end;
|
|
|
|
Trie* searchPrefix(string prefix)
|
|
{
|
|
Trie* node = this;
|
|
for (char ch : prefix) {
|
|
if (node->m_children[ch - 'a'] == nullptr) {
|
|
return nullptr;
|
|
}
|
|
node = node->m_children[ch - 'a'];
|
|
}
|
|
return node;
|
|
}
|
|
|
|
public:
|
|
Trie() :
|
|
m_children(26),
|
|
is_end(false)
|
|
{
|
|
|
|
}
|
|
|
|
void insert(string word)
|
|
{
|
|
Trie* node = this;
|
|
for (char ch : word) {
|
|
if (node->m_children[ch - 'a'] == nullptr) {
|
|
node->m_children[ch - 'a'] = new Trie;
|
|
}
|
|
node = node->m_children[ch - 'a'];
|
|
}
|
|
node->is_end = true;
|
|
}
|
|
|
|
bool search(string word)
|
|
{
|
|
Trie* node = searchPrefix(word);
|
|
return node != nullptr && node->is_end;
|
|
}
|
|
|
|
bool startsWith(string prefix)
|
|
{
|
|
return searchPrefix(prefix) != nullptr;
|
|
}
|
|
}; |