Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Node{
- public :
- vector<Node*>v = vector<Node*>(26, NULL);
- bool isEnd = false;
- };
- class Trie {
- public:
- Node* root;
- Trie() { root = new Node(); }
- //=====================================================================
- void insert(string word)
- {
- //DON'T MODIFY ROOT
- Node* currNode = root; //temporary pointer (currNode) for traversal
- for (int i = 0; i < word.size(); i++)
- {
- int chIdx = word[i] - 'a';
- if (currNode->v[chIdx] == NULL)
- currNode->v[chIdx] = new Node();
- currNode = currNode->v[chIdx];
- }
- currNode->isEnd = true;
- }
- //============================================================================
- Node* getPrefixEndNode(string& word)
- {
- Node* currNode = root;
- for (int i = 0; i < word.size(); i++)
- {
- int chIdx = word[i] - 'a';
- if (currNode->v[chIdx] == NULL) return NULL;
- currNode = currNode->v[chIdx];
- }
- return currNode;
- }
- //================================================================================
- bool search(string word)
- {
- Node* prefixEndNode = getPrefixEndNode(word);
- if (prefixEndNode == NULL) return false;
- return (prefixEndNode->isEnd);
- }
- //=================================================================================
- bool startsWith(string prefix)
- {
- Node* prefixEndNode = getPrefixEndNode(prefix);
- if (prefixEndNode == NULL) return false;
- return true;
- }
- };
- /**
- * Your Trie object will be instantiated and called as such:
- * Trie* obj = new Trie();
- * obj->insert(word);
- * bool param_2 = obj->search(word);
- * bool param_3 = obj->startsWith(prefix);
- */
Advertisement
Add Comment
Please, Sign In to add comment