spider68

Trie implementation

May 16th, 2020
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1. class Trie {
  2. public:
  3.     Trie() {}
  4.  
  5.     void insert(string word) {
  6.         Trie* node = this;
  7.         for (char ch : word) {
  8.             if (node->next.find(ch)==node->next.end()) { node->next[ch] = new Trie(); }
  9.             node = node->next[ch];
  10.         }
  11.         node->isword = true;
  12.     }
  13.  
  14.     bool search(string word) {
  15.         Trie* node = this;
  16.         for (char ch : word) {
  17.             if (node->next.find(ch)==node->next.end()) { return false; }
  18.             node = node->next[ch];
  19.         }
  20.         return node->isword;
  21.     }
  22.  
  23.     bool startsWith(string prefix) {
  24.         Trie* node = this;
  25.         for (char ch : prefix) {
  26.             if (node->next.find(ch)==node->next.end()) { return false; }
  27.             node = node->next[ch];
  28.         }
  29.         return true;
  30.     }
  31.  
  32. private:
  33.     map<char, Trie*> next = {};
  34.     bool isword = false;
  35. };
Add Comment
Please, Sign In to add comment