jayati

Implement Trie (Prefix Tree)

Mar 16th, 2023
222
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.81 KB | None | 0 0
  1. class Node{
  2.     public :
  3.     vector<Node*>v = vector<Node*>(26, NULL);
  4.     bool isEnd = false;
  5. };
  6. class Trie {
  7. public:
  8.     Node* root;
  9.     Trie() { root = new Node(); }
  10.     //=====================================================================
  11.     void insert(string word)
  12.     {
  13.         //DON'T MODIFY ROOT
  14.         Node* currNode = root; //temporary pointer (currNode) for traversal
  15.         for (int i = 0; i < word.size(); i++)
  16.         {
  17.             int chIdx = word[i] - 'a';
  18.             if (currNode->v[chIdx] == NULL)
  19.                 currNode->v[chIdx] = new Node();
  20.             currNode = currNode->v[chIdx];
  21.         }
  22.         currNode->isEnd = true;
  23.     }
  24.     //============================================================================
  25.     Node* getPrefixEndNode(string& word)
  26.     {
  27.         Node* currNode = root;
  28.         for (int i = 0; i < word.size(); i++)
  29.         {
  30.             int chIdx = word[i] - 'a';
  31.             if (currNode->v[chIdx] == NULL) return NULL;
  32.             currNode = currNode->v[chIdx];
  33.         }
  34.         return currNode;
  35.     }
  36.     //================================================================================
  37.     bool search(string word)
  38.     {
  39.         Node* prefixEndNode = getPrefixEndNode(word);
  40.         if (prefixEndNode == NULL) return false;
  41.         return (prefixEndNode->isEnd);
  42.     }
  43.     //=================================================================================
  44.     bool startsWith(string prefix)
  45.     {
  46.         Node* prefixEndNode = getPrefixEndNode(prefix);
  47.         if (prefixEndNode == NULL) return false;
  48.         return true;
  49.     }
  50. };
  51.  
  52. /**
  53.  * Your Trie object will be instantiated and called as such:
  54.  * Trie* obj = new Trie();
  55.  * obj->insert(word);
  56.  * bool param_2 = obj->search(word);
  57.  * bool param_3 = obj->startsWith(prefix);
  58.  */
Advertisement
Add Comment
Please, Sign In to add comment