Skip to content

Instantly share code, notes, and snippets.

@AbstractXan
Created May 15, 2020 02:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AbstractXan/81116f3583aa52d784e4d69ea88e0062 to your computer and use it in GitHub Desktop.
Save AbstractXan/81116f3583aa52d784e4d69ea88e0062 to your computer and use it in GitHub Desktop.
Trie implementation
#include<unordered_map> // O(1) fetch and insert
#include<tuple>
class Trie {
public:
struct node {
bool isEnd;
unordered_map<char,node*> children;
// node(){isEnd=true;children=NULL;}
node(bool b){isEnd=b;}
};
node *head;
/** Initialize your data structure here. */
Trie() {
head = new node(false);
}
/** Inserts a word into the trie. */
void insert(string word) {
tuple<bool,node*,int> t = traverse(word);
node* n = get<1>(t);
// If complete word traversal exists
if (get<0>(t)){
if (n->isEnd==false){
n->isEnd=true;
}
return;
}
node* temp;
// Go till last word.
for (int i=get<2>(t) ; i<word.length(); i++){
// Create a new node
// Set false if not end of word
temp = new node((i==word.length()-1));
// Add to its child
n->children[word[i]]=temp;
// Update n
n = temp;
}
}
/** Returns if the word is in the trie. */
bool search(string word) {
tuple<bool,node*,int> v = traverse(word);
// If correct traversal AND the last node is end of a word
return (get<0>(v) && get<1>(v)->isEnd);
}
// Returns if there exists a traversal, Returns Last Node and String pointer
tuple<bool,node*,int> traverse(string prefix) {
string s = prefix;
node* n = head;
int i=0;
unordered_map<char,node*>::iterator it;
// Traverses as much as possible
while (i<s.length()){
it = n->children.find(s[i]);
// If not found
if (it==n->children.end()){
return make_tuple(false,n,i);
}
n = it->second;
i++;
}
// If all through. There exists a word
return make_tuple(true,n,i);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
tuple<bool,node*,int> v = traverse(prefix);
return get<0>(v);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment