Skip to content

Instantly share code, notes, and snippets.

@sourabh2k15
Created December 26, 2017 04:13
Show Gist options
  • Save sourabh2k15/d31465851047a4b6c147d41f78c3dee8 to your computer and use it in GitHub Desktop.
Save sourabh2k15/d31465851047a4b6c147d41f78c3dee8 to your computer and use it in GitHub Desktop.
Leetcode #208 Simple Trie Implementation
class Trie {
private:
class TrieNode{
public:
bool isWord;
vector<TrieNode*> next;
TrieNode() : next(vector<TrieNode*>(26, NULL)), isWord(false){}
~TrieNode(){
for(auto node: next) delete node;
}
};
TrieNode* root;
public:
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
~Trie(){
delete root;
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* p = root;
for(int i = 0; i < word.length(); i++){
char c = word[i];
if(p->next[c - 'a'] == NULL) p->next[c - 'a'] = new TrieNode();
p = p->next[c - 'a'];
}
p->isWord = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode* p = find(word);
return p != NULL && p->isWord;
}
TrieNode* find(string word){
TrieNode* p = root;
for(int i = 0; i < word.length() && p != NULL; i++){
char c = word[i];
p = p->next[c - 'a'];
}
return p;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
return find(prefix) != NULL;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment