class Trie {
public:
/** Initialize your data structure here. */
Trie() {
root_ = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
TrieNode* p = root_;
for (const char c : word) {
if (!p->children[c - 'a']) {
p->children[c - 'a'] = new TrieNode();
}
p = p->children[c - 'a'];
}
p->is_word = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
TrieNode* p = find(word);
return (p && p->is_word);
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
return find(prefix) != nullptr;
}
private:
// two basic: is_word: whether it is the end of a word
// children : implement it with vector, storing the pointer to the child nodes
struct TrieNode {
bool is_word;
vector<TrieNode*> children;
TrieNode():is_word(false),children(26,nullptr){}
~TrieNode() {
for (auto child : children) {
if (child) delete child;
}
}
};
// common function for realizing search & startwith
TrieNode* find(const string& prefix) {
TrieNode* p = root_;
for (char c : prefix) {
p = p->children[c - 'a'];
if (p == nullptr) break;
}
return p;
}
TrieNode* root_;
};
【思路】
前缀树的基本结构是一个最多有26个children的树
网友评论