|
| 1 | +/* |
| 2 | +
|
| 3 | +if the words are : GOAT, GOAL , HELLO, HEY |
| 4 | +then in trie they are stored as |
| 5 | + Root |
| 6 | + / \ |
| 7 | + G H |
| 8 | + / \ |
| 9 | + O E |
| 10 | + / / \ |
| 11 | + A Y L |
| 12 | + / \ \ |
| 13 | + T L L |
| 14 | + \ |
| 15 | + O |
| 16 | +
|
| 17 | +
|
| 18 | +*/ |
| 19 | +#include <string> |
| 20 | +#include <vector> |
| 21 | +#include <map> |
| 22 | +#include <iostream> |
| 23 | + |
| 24 | +struct TrieNode { |
| 25 | + std::string val; |
| 26 | + std::map<const char, TrieNode*> Children = {}; |
| 27 | + bool isEnd; |
| 28 | + TrieNode() { isEnd = false; } |
| 29 | +}; |
| 30 | + |
| 31 | +void addToTrie(std::string s, TrieNode* root); |
| 32 | + |
| 33 | +void setupTrie(std::vector<std::string> words, TrieNode* root){ |
| 34 | + for(auto& j : words){ |
| 35 | + addToTrie(j, root); |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +void addToTrie(std::string s, TrieNode* root){ |
| 40 | + TrieNode* curr = root; |
| 41 | + |
| 42 | + for(int i = 0; i < s.size(); i++){ |
| 43 | + char next = s[i]; |
| 44 | + TrieNode* currNode = curr->Children[next]; |
| 45 | + //if the current node doesn't exist, add it |
| 46 | + if(!currNode){ |
| 47 | + currNode = new TrieNode(); |
| 48 | + curr->Children[s[i]] = currNode; |
| 49 | + } |
| 50 | + curr = currNode; |
| 51 | + } |
| 52 | + |
| 53 | + curr->isEnd = true; |
| 54 | +} |
| 55 | + |
| 56 | +bool isMember(std::string word, TrieNode* root){ |
| 57 | + TrieNode* curr = root; |
| 58 | + |
| 59 | + for(int i = 0; i < word.length(); i++){ |
| 60 | + const char next = word[i]; |
| 61 | + TrieNode* currNode = curr->Children[next]; |
| 62 | + if(!currNode) |
| 63 | + return 0; |
| 64 | + curr = currNode; |
| 65 | + } |
| 66 | + return curr->isEnd; |
| 67 | +} |
| 68 | + |
| 69 | + |
| 70 | +//driver |
| 71 | +int main(){ |
| 72 | + std::vector<std::string> words = {"hello", "hi", "yes", "you"}; |
| 73 | + |
| 74 | + TrieNode* root = new TrieNode(); |
| 75 | + setupTrie(words, root); |
| 76 | + std::string s = "hello"; |
| 77 | + std::string s2 = "help"; |
| 78 | + |
| 79 | + if(isMember(s,root)) |
| 80 | + std::cout << "hello is a member\n "; |
| 81 | + else |
| 82 | + std::cout << "hello not a member\n"; |
| 83 | + |
| 84 | + if(isMember(s2, root)) |
| 85 | + std::cout<<"help is a member\n"; |
| 86 | + else |
| 87 | + std::cout <<"help is not a member\n"; |
| 88 | + |
| 89 | + return 0; |
| 90 | +} |
0 commit comments