matbensch

Trie C++

Jan 28th, 2023
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.92 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <map>
  4.  
  5. using namespace std;
  6.  
  7. int K = 26;
  8.  
  9. struct node
  10. {
  11.     vector<node*> child;
  12.     bool leaf = false;
  13.     int freq = 0;
  14.  
  15.     node()
  16.     {
  17.         child.assign(26, nullptr);
  18.     }
  19.  
  20. };
  21.  
  22. node* root = new node();
  23.  
  24. void add(string s)
  25. {
  26.     node* cur = root;
  27.     for(char c : s)
  28.     {
  29.         if(cur->child[c-'a'] == nullptr) cur->child[c-'a'] = new node();
  30.         cur = cur->child[c-'a'];
  31.     }
  32.     cur->leaf = true;
  33.     cur->freq++;
  34. }
  35.  
  36. bool contains(string s)
  37. {
  38.     node* cur = root;
  39.     for(char c : s)
  40.     {
  41.         if(cur->child[c-'a'] == nullptr) return false;
  42.         cur = cur->child[c-'a'];
  43.     }
  44.     return true;
  45. }
  46.  
  47. int main()
  48. {
  49.     add("abc");
  50.     add("abd");
  51.     add("bad");
  52.     add("badc");
  53.  
  54.     cout << "Contains abd? "<<(contains("abd")?"Yes.\n":"No.\n");
  55.     cout << "Contains badd? "<<(contains("badd")?"Yes.\n":"No.\n");
  56.  
  57. }
Advertisement
Add Comment
Please, Sign In to add comment