208. Implement Trie (Prefix Tree)
Medium
176334FavoriteShare
Implement a trie with insert
, search
, and startsWith
methods.
Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple"); // returns true
trie.search("app"); // returns false
trie.startsWith("app"); // returns true
trie.insert("app");
trie.search("app"); // returns true
class TrieNode{
public:
TrieNode *child[26];
bool IsWord;
TrieNode(){
for(auto &c:child){
c = NULL;
}
IsWord = false;
}
};
class Trie{
private:
TrieNode* root;
public:
Trie(){
root = new TrieNode();
}
void insert(string word){
TrieNode* pNode = root;
for(int i = 0;i < word.length();i ++){
if(pNode->child[word[i] - 'a'] == NULL){
pNode->child[word[i] - 'a'] = new TrieNode();
}
pNode = pNode->child[word[i] - 'a'];
}
pNode->IsWord = true;
}
bool search(string word){
TrieNode* pNode = root;
for(int i = 0;i < word.length();i ++){
if(pNode->child[word[i] - 'a'] == NULL){
return false;
}
pNode = pNode->child[word[i] - 'a'];
}
if(pNode->IsWord){return true;}
else{return false;}
}
bool startsWith(string prefix){
TrieNode* pNode = root;
for(int i = 0;i < prefix.length();i ++){
if(pNode->child[prefix[i] - 'a'] == NULL){
return false;
}
pNode = pNode->child[prefix[i] - 'a'];
}
return true;
}
};