ProgMe

Untitled

Dec 30th, 2023
901
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.94 KB | None | 0 0
  1. class Trie {
  2.     struct Node {
  3.         bool is_end = false;
  4.  
  5.         map<char, Node *> next;
  6.     };
  7.  
  8.     Node* root = nullptr;
  9.  
  10. public:
  11.     Trie();
  12.  
  13.     void insert(string s);
  14.  
  15.     void erase(string s);
  16.  
  17.     bool check(string s);
  18. };
  19.  
  20. Trie::Trie() {
  21.     root = new Node();
  22. }
  23.  
  24. void Trie::insert(std::string s) {
  25.     Node* cur = root;
  26.  
  27.     for (auto i : s) {
  28.         if (!cur->next[i]) {
  29.             cur->next[i] = new Node();
  30.         }
  31.         cur = cur->next[i];
  32.     }
  33.  
  34.     cur->is_end = true;
  35. }
  36.  
  37. void Trie::erase(string s) {
  38.     Node* cur = root;
  39.    
  40.     for (auto i : s) {
  41.         if (!cur->next[i]) {
  42.             return;
  43.         }
  44.         cur = cur->next[i];
  45.     }
  46.    
  47.     cur->is_end = false;
  48. }
  49.  
  50. bool Trie::check(string s) {
  51.     Node* cur = root;
  52.  
  53.     for (auto i : s) {
  54.         if (!cur->next[i]) {
  55.             return false;
  56.         }
  57.         cur = cur->next[i];
  58.     }
  59.    
  60.     return cur->is_end;
  61. }
Advertisement
Add Comment
Please, Sign In to add comment