initialize repository of algorithm-template

This commit is contained in:
2025-08-08 23:09:34 +08:00
commit a876627598
19 changed files with 363 additions and 0 deletions

49
trie-tree/trie-tree.cpp Normal file
View File

@@ -0,0 +1,49 @@
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;
}
};