208. Implement Trie (Prefix Tree)
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
Note:
You may assume that all inputs are consist of lowercase letters a-z.
All inputs are guaranteed to be non-empty strings.
刚开始写的代码如下:
typedef struct Trie {
struct Trie * next[26];
bool isWord;
} Trie;
/** Initialize your data structure here. */
Trie g_pool[1000];
int g_pool_idx;
Trie* trieCreate() {
g_pool_idx = 0;
int i;
for(i = 0; i < 26; ++i)
{
g_pool[0].next[i] = NULL;
}
g_pool[0].isWord = false;
return g_pool + g_pool_idx++;
}
/** Inserts a word into the trie. */
void trieInsert(Trie* obj, char * word) {
while(*word != '\0')
{
int idx = *word - 'a';
if(obj->next[idx] == NULL)
{
obj->next[idx] = g_pool +g_pool_idx++;
int i;
Trie *p= obj->next[idx];
for(i = 0; i < 26; ++i)
{
p->next[idx] = NULL;
}
p->isWord = false;
}
++word;
if(*word == '\0')
{
obj->next[idx]->isWord = true;
}
obj = obj->next[idx];
}
}
/** Returns if the word is in the trie. */
bool trieSearch(Trie* obj, char * word) {
while(*word != '\0')
{
int idx = *word -'a';
if(obj->next[idx] == NULL)
{
return false;
}
++word;
if(*word == '\0' && obj->next[idx]->isWord == false)
{
return false;
}
obj = obj->next[idx];
}
return true;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool trieStartsWith(Trie* obj, char * prefix) {
while(*prefix != '\0')
{
int idx = *prefix - 'a';
if(obj->next[idx] == NULL)
{
return false;
}
++prefix;
obj = obj->next[idx];
}
return true;
}
void trieFree(Trie* obj) {
g_pool_idx = 0;
}
/**
* Your Trie struct will be instantiated and called as such:
* Trie* obj = trieCreate();
* trieInsert(obj, word);
* bool param_2 = trieSearch(obj, word);
* bool param_3 = trieStartsWith(obj, prefix);
* trieFree(obj);
*/
提交报错:
执行出错信息: Line 41: Char 33: runtime error: member access within null pointer of type 'struct Trie' (solution.c)
最后执行的输入: ["Trie","insert","search","search","insert","search","insert","search"] [[],["abc"],["abc"],["ab"],["ab"],["ab"],["ab"],["ab"]]
但把测试用例改成上面的这个,又是可以通过的。。
根据错误提示,加上 assert,发现是 obj->next[idx]为空指针。。
这就很怪了,前面已经判断,如果是空,会分配buffer的。
后来发现trieInsert()里的一段代码有问题:
for(i = 0; i < 26; ++i)
{
p->next[idx] = NULL;
}
改成下面的后,再次提交,就通过了。。
for(i = 0; i < 26; ++i)
{
p->next[i] = NULL;
}