class Trie {
public:
bool isend;
Trie* next[26];
/** Initialize your data structure here. */
Trie() {
isend = false;
memset(next,0,sizeof(next));
}
/** Inserts a word into the trie. */
void insert(string word) {
Trie* node = this;
for(char c : word){
if(node->next[c - 'a'] == NULL){
node->next[c - 'a'] = new Trie;
}
node = node->next[c - 'a'];
}
node->isend = true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
Trie* node = this;
for(char c : word){
node = node->next[c - 'a'];
if(node == NULL){
return false;
}
}
return node->isend;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
Trie* node = this;
for(char c : prefix){
node = node->next[c - 'a'];
if(node == NULL){
return false;
}
}
return true;
}
};
字典树基础功能实现 力扣208.实现Trie
最新推荐文章于 2023-11-27 10:22:59 发布