208. Implement Trie (Prefix Tree)
class TrieNode {
public:
bool is_end;
vector<TrieNode*> children = vector<TrieNode*>(26, nullptr); //明确这是一个成员变量声明;
TrieNode() {
is_end = false;}
};
class Trie {
public:
TrieNode* root = new TrieNode();
TrieNode* p;
/** Initialize your data structure here. */
Trie() {
}
/** Inserts a word into the trie. */
void insert(string word) {
int len = word.size();
p = root;
for(int ii = 0; ii < len; ii++) {
if(!p->children[word[ii] - 'a']) p->children[word[ii] - 'a'] = new TrieNode();
p = p->children[word[ii] - 'a'];
}
p->is_end = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
int len = word.size();
p = root;
for(int ii = 0; ii < len; ii++) {
if(!p->children[word[ii] - 'a']) return false;
p = p->children[word[ii] - 'a'];
}
return p->is_end;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
int len = prefix.size();
p = root;
for(int ii = 0; ii < len; ii++) {
if(!p->children[prefix[ii] - 'a']) return false;
p = p->children[prefix[ii] - 'a'];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/