ann8497

trie

Sep 1st, 2019 (edited)
802
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.31 KB | None | 0 0
  1. /****
  2. for iterating the bits of the number
  3.         bitset<32>b(n);
  4.         for(int i=31;i>=0;i--)
  5.         {
  6. ***/
  7.  
  8. #include<bits/stdc++.h>
  9. using namespace std;
  10.  
  11. #define hashmap unordered_map<char, node*>
  12.  
  13. class node{
  14.   public:
  15.     char data;
  16.     hashmap h;
  17.     bool isTerminal;
  18.     node(char c){
  19.         data = c;
  20.         isTerminal = false;
  21.     }
  22. };
  23.  
  24.  
  25. class trie{
  26.   node *root;
  27.   public:
  28.     trie(){
  29.         root = new node('\0');
  30.     }
  31.    void addWord(char *word){
  32.        node*temp = root;
  33.        for(int i = 0; word[i]!='\0';i++){
  34.            char ch = word[i];
  35.            if(temp->h.count(ch) == 0){
  36.                node*child = new node(ch);
  37.                temp->h[ch] = child;
  38.                temp = child;
  39.            }
  40.            else
  41.            temp = temp->h[ch];
  42.        }
  43.        temp->isTerminal = true;
  44.    }
  45.    bool search(char *word){
  46.        node*temp = root;
  47.         for(int i = 0; word[i]!='\0';i++){
  48.             char ch = word[i];
  49.             if(temp->h.count(ch) == 0)
  50.             return false;
  51.             else
  52.             temp = temp->h[ch];
  53.         }
  54.         return temp->isTerminal;
  55.    }
  56.  
  57.    
  58. };
  59.  
  60. int main(){
  61.    
  62.     char word[10][100] = {"ankit", "mittal"};
  63.     trie t;
  64.     t.addWord(word[0]);
  65.     t.addWord(word[1]);
  66.     cout<<t.search(word[0]);
  67.    
  68. }
Advertisement
Add Comment
Please, Sign In to add comment