208 Implement Trie (Prefix Tree)
Implement a trie with insert, search, and startsWith methods.
Solution
class TrieNode {
public:
char val;
// NOTE THIS!!!
bool isEnd;
map<char, TrieNode*> children;
// Initialize your data structure here.
TrieNode(): isEnd(false){
}
TrieNode(char c): val(c), isEnd(false) {}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
TrieNode* p = root;
int n = word.size();
for ( int i = 0; i <= n-1; i++ ) {
char c = word[i];
if ( p->children.find(c) != p->children.end() ) p = p->children[c];
else {
TrieNode *node = new TrieNode(c);
p->children[c] = node;
p = p->children[c];
}
}
p->isEnd = true;
return;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode* p = lastP(word);
if ( p == NULL ) return false;
return p->isEnd;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode* p = lastP(prefix);
return ( p != NULL );
}
private:
TrieNode* root;
TrieNode* lastP(string s) {
TrieNode* p = root;
int n = s.size();
for ( int i = 0; i <= n-1; i++ ) {
char c = s[i];
if ( p->children.find(c) == p->children.end() ) {return NULL;}
else p = p->children[c];
}
return p;
}
};
// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");