Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include "iostream"
- #include <utility>
- #include <vector>
- using namespace std;
- class Trie
- {
- private:
- class Node
- {
- public:
- bool endOfTheWord = 0;
- char ch{};
- vector<Node *> deti;
- explicit Node(char k) : ch(k)
- {}
- Node()
- {}
- Node *search(char c)
- {
- for (Node *current : deti)
- {
- if (current->ch == c)
- return current;
- }
- return nullptr;
- }
- Node *insertCharacter(char c)
- {
- Node *find_result = search(c);
- if (find_result)
- return find_result;
- Node *new_node = new Node(c);
- deti.push_back(new_node);
- return new_node;
- }
- ~Node()
- {
- for (int i = 0; i < deti.size(); ++i)
- {
- delete deti[i];
- }
- }
- };
- public:
- Node *_root;
- Trie() : _root(new Node())
- {}
- void retrieveFunc(Node *currNode, const string &currPref)
- {
- if (currNode->endOfTheWord)
- cout << currPref << std::endl;
- for (Node *child : currNode->deti)
- retrieveFunc(child, currPref + child->ch);
- }
- Node *eraseFunc(string k, Node *currNode, int depth)
- {
- if (!currNode)
- return nullptr;
- if (depth == k.length())
- {
- currNode->endOfTheWord = false;
- if (currNode->deti.empty())
- {
- Node *tmp = currNode;
- delete currNode;
- return tmp;
- } else
- {
- }
- } else
- {
- }
- Node *detyo = eraseFunc(k, currNode->search(k[depth]), depth + 1);
- if (!currNode->endOfTheWord)
- if (currNode->deti.empty())
- currNode = nullptr;
- return currNode;
- }
- bool keyInTrie(const string &key) const
- {
- Node *x = _root;
- for (char i : key)
- {
- x = x->search(i);
- if (!x)
- return false;
- }
- return x->endOfTheWord;
- }
- Node *insertKey(const string &k) const
- {
- Node *x = _root;
- for (char i : k)
- x = x->insertCharacter(i);
- x->endOfTheWord = true;
- return x;
- }
- void getAllWordsByPrefix(const string &pref)
- {
- Node *last = _root;
- for (char i : pref)
- {
- last = last->search(i);
- if (!last)
- return;
- }
- retrieveFunc(last, pref);
- }
- void eraser(string key)
- {
- _root = eraseFunc(std::move(key), _root, 0);
- }
- };
- signed main()
- {
- string input, prefix, word;
- cin >> input >> prefix;
- Trie trie = Trie();
- for (char c : input)
- {
- if (c == '$')
- {
- trie.insertKey(word);
- } else if (c == '#')
- {
- word.pop_back();
- } else
- {
- word.push_back(c);
- }
- }
- trie.getAllWordsByPrefix(prefix);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement