ann8497

trie

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