|
| 1 | +#include<iostream> |
| 2 | +#include<unordered_map> |
| 3 | +#include<cstring> |
| 4 | +#include<vector> |
| 5 | +usingnamespacestd; |
| 6 | + |
| 7 | +//Build a Prefix Tree - Trie |
| 8 | +classNode{ |
| 9 | +public: |
| 10 | +char data; |
| 11 | +unordered_map<char,Node*> children; |
| 12 | +bool isTerminal; |
| 13 | + |
| 14 | +Node(char d){ |
| 15 | +data = d; |
| 16 | +isTerminal =false; |
| 17 | +} |
| 18 | +}; |
| 19 | + |
| 20 | +classTrie{ |
| 21 | +public: |
| 22 | +Node*root; |
| 23 | + |
| 24 | +Trie(){ |
| 25 | +root =newNode('\0'); |
| 26 | +} |
| 27 | + |
| 28 | +voidinsert(string word){ |
| 29 | + |
| 30 | +Node* temp = root; |
| 31 | + |
| 32 | +for(char ch : word){ |
| 33 | + |
| 34 | +if(temp->children.count(ch)==0){ |
| 35 | +Node *n =newNode(ch); |
| 36 | +temp->children[ch] = n; |
| 37 | +} |
| 38 | +temp = temp->children[ch]; |
| 39 | +} |
| 40 | + |
| 41 | +temp->isTerminal =true; |
| 42 | +} |
| 43 | +}; |
| 44 | + |
| 45 | +voidsearchHelper(Trie t, string document,int i, unordered_map<string,bool> &m ){ |
| 46 | + |
| 47 | +Node*temp = t.root; |
| 48 | +for(int j = i; j < document.length();j++){ |
| 49 | +char ch = document[j]; |
| 50 | +if(temp->children.count(ch)==0){ |
| 51 | +return; |
| 52 | +} |
| 53 | +temp = temp->children[ch]; |
| 54 | +if(temp->isTerminal){ |
| 55 | +//history part |
| 56 | +string out = document.substr(i,j-i+1); |
| 57 | +m[out] =true; |
| 58 | +} |
| 59 | + |
| 60 | +} |
| 61 | +return; |
| 62 | + |
| 63 | +} |
| 64 | + |
| 65 | +voiddocumentSearch(string document, vector<string> words){ |
| 66 | + |
| 67 | +//1. Create a trie of words |
| 68 | +Trie t; |
| 69 | +for(string w : words){ |
| 70 | +t.insert(w); |
| 71 | +} |
| 72 | + |
| 73 | +//2. Searching (Helper Fn) |
| 74 | +unordered_map<string,bool> m; |
| 75 | +for(int i=0;i<document.length();i++){ |
| 76 | +searchHelper(t, document, i, m); |
| 77 | +} |
| 78 | + |
| 79 | +//3. You can check which words are marked as True inside Hashmap |
| 80 | +for(auto w :words){ |
| 81 | +if(m[w]){ |
| 82 | +cout<<w <<" : True" <<endl; |
| 83 | +} |
| 84 | +else{ |
| 85 | +cout<<w <<" : False"<<endl; |
| 86 | +} |
| 87 | +} |
| 88 | + |
| 89 | +return; |
| 90 | +} |
| 91 | + |
| 92 | + |
| 93 | +intmain(){ |
| 94 | + |
| 95 | + string document ="little cute cat loves to code in c++, java & python"; |
| 96 | + vector<string> words{"cute cat","ttle","cat","quick","big"}; |
| 97 | + |
| 98 | +documentSearch(document,words); |
| 99 | + |
| 100 | + |
| 101 | +return0; |
| 102 | +} |
| 103 | + |