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 *children[26];
bool leaf;
TrieNode() {
for(int i=0;i<26;i++)
{
children[i]=nullptr;
}
leaf=false;
}
};
class Trie {
public:
Trie() {
root = new TrieNode();
}
// Inserts a word into the trie.
void insert(string word) {
TrieNode *tmp=root;
for(int i=0;i<word.size();i++)
{
if(tmp->children[word[i]-'a']==nullptr) tmp->children[word[i]-'a']=new TrieNode();
tmp=tmp->children[word[i]-'a'];
}
tmp->leaf=true;
}
// Returns if the word is in the trie.
bool search(string word) {
TrieNode *tmp=root;
for(int i=0;i<word.size();i++)
{
if(tmp->children[word[i]-'a']==nullptr) return false;
tmp=tmp->children[word[i]-'a'];
}
if(tmp->leaf) return true;
return false;
}
// Returns if there is any word in the trie
// that starts with the given prefix.
bool startsWith(string prefix) {
TrieNode *tmp=root;
for(int i=0;i<prefix.size();i++)
{
if(tmp->children[prefix[i]-'a']==nullptr) return false;
tmp=tmp->children[prefix[i]-'a'];
}
return true;
}
private:
TrieNode* root;
};
// Your Trie object will be instantiated and called as such:
// Trie trie;
// trie.insert("somestring");
// trie.search("key");