刷题208. Implement Trie (Prefix Tree)
Posted siweihz
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了刷题208. Implement Trie (Prefix Tree)相关的知识,希望对你有一定的参考价值。
一、题目说明
题目208. Implement Trie (Prefix Tree),实现trie,包括insert、search、startsWith。
二、我的解答
Trie树,又叫“字典树”,“前缀树”。实现代码如下:
class Trie{
public:
Trie(){
isEnd = false;
memset(next,0,sizeof(next));
}
~Trie(){
for(int i=0;i<26;i++){
if(next[i] == NULL){
continue;
}else{
delete(next[i]);
next[i] = NULL;
}
}
}
void insert(string word){
Trie* node = this;
for(char c: word){
int cur = c - ‘a‘;
if(node->next[cur] == NULL){
node->next[cur] = new Trie();
}
node = node->next[cur];
}
node->isEnd = true;
}
bool search(string word){
Trie* node = this;
for(char c: word){
int cur = c - ‘a‘;
node = node->next[cur];
if(node == NULL){
return false;
}
}
return node->isEnd;
}
bool startsWith(string prefix){
Trie* node = this;
for(char c: prefix){
int cur = c - ‘a‘;
node = node->next[cur];
if(node == NULL){
return false;
}
}
return true;
}
private:
bool isEnd;
Trie* next[26];
};
性能如下:
Runtime: 84 ms, faster than 54.43% of C++ online submissions for Implement Trie (Prefix Tree).
Memory Usage: 45.9 MB, less than 20.00% of C++ online submissions for Implement Trie (Prefix Tree).
三、优化措施
以上是关于刷题208. Implement Trie (Prefix Tree)的主要内容,如果未能解决你的问题,请参考以下文章
208. Implement Trie (Prefix Tree)
208. Implement Trie (Prefix Tree)
208. Implement Trie (Prefix Tree)
208. Implement Trie (Prefix Tree)