Implement Trie (Prefix Tree)
Implement a trie with insert, search, and startsWith methods.
Note:
You may assume that all inputs are consist of lowercase letters a-z.
class TrieNode {
public:
// Initialize your data structure here.
TrieNode() {
memset(next, NULL, sizeof(next));
someWordEndHere = false;
}
TrieNode* next[26];
bool someWordEndHere;
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
int len = word.length();
TrieNode *p = root;
for(int i = 0; i < len; i++){
int id = word[i]-'a';
if(p->next[id] == NULL){
p->next[id] = new TrieNode();
} p = p->next[id];
} p->someWordEndHere = true;
}
// Returns if the word is in the trie.
bool search(string word) {
int len = word.length();
TrieNode *p = root;
for(int i = 0; i < len; i++){
int id = word[i]-'a';
if(p->next[id] == NULL) return false;
p = p->next[id];
} return p->someWordEndHere;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
int len = prefix.length();
TrieNode *p = root;
for(int i = 0; i < len; i++){
int id = prefix[i]-'a';
if(p->next[id] == NULL) return false;
p = p->next[id];
} return true;
}
private:
TrieNode* root;
};
// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");