1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75
| class Trie { public: Trie() { root = new Node(); } void insert(string word) { int start = -1; Node* point = root; while(++start < word.size()) { if(!travesalChilds(word, start, point)) { point->childs.push_back(new Node(word[start])); point = point->childs.back(); } } point->endOfWord = true; } bool search(string word) { Node* point = root; int start = -1; while(++start < word.size()) { if(!travesalChilds(word, start, point)) return false; } return point->endOfWord; } bool startsWith(string prefix) { Node* point = root; int start = -1; while(++start < prefix.size()) { if(!travesalChilds(prefix, start, point)) return false; } return true; } private: struct Node { bool endOfWord = false; char val; vector<Node*> childs; Node() = default; Node(char val, bool end = false) : val(val), endOfWord(end) {}; }; Node* root; bool travesalChilds(string& s, int& start, Node*& node) { for(auto& child : node->childs) { if(child->val == s[start]) { node = child; return true; } } return false; } };
|