dijkstra及并查集算法更新
This commit is contained in:
49
trie-tree.cpp
Normal file
49
trie-tree.cpp
Normal 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;
|
||||
}
|
||||
};
|
Reference in New Issue
Block a user