添加字典树、并查集、Dijkstra算法

This commit is contained in:
2025-06-03 16:30:03 +08:00
parent 3015523239
commit 9a5e746691
3 changed files with 120 additions and 0 deletions

49
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;
}
};