class Trie {
public:
// 定义字典树 : 根节点为空 其余节点时一个字符
struct TrieNode{
// 字典树一个节点
bool isEnd;
TrieNode *child[26];//记录经过该节点的子树 没有则即为NULL
TrieNode():isEnd(false){
//这里:等价于in a要使用引用 不然修改无效
for(auto &a : child)
a = NULL;
}
};
TrieNode *root;
/** Initialize your data structure here. */
Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
// 在遍历过程中插入 如果不存在就创建一个新的trienode节点挂载这里
// 注意字母顺序即为数组顺序
TrieNode *node = root;
for(auto &s : word){// s即为一个字符
int pos = s - 'a';
if(node->child[pos] == NULL){
node->child[pos] = new TrieNode();
}
node = node->child[pos];
}
node->isEnd = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
// 从root节点遍历 到isEnd结束才算查找到
TrieNode *node = root;
for(auto s : word){
int pos = s - 'a';
if(node->child[pos] == NULL) return false;
node = node->child[pos];
}
return node->isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
TrieNode *node = root;
for(auto s : prefix){
int pos = s - 'a';
if(node->child[pos] == NULL) return false;
node = node->child[pos];
}
return true;
}
};
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