我已经使用视频来理解前缀 trie(尽管最终我试图到达后缀 trie)但是示例代码的链接已损坏,所以我从视频中想出了这个,有两个函数,即插入并搜索如下
void insert(string word)
{
node* current=head;
current->prefix_count++;
for(unsigned int i=0;i<word.length();++i)
{
int letter=(int)word[i]-(int)'a';
if (current->child[letter]==NULL)
current->child[letter]=new node();
current->child[letter]->prefix_count++;
current=current->child[letter];
}
current->is_end=true;
}
bool search(string word)
{
node *current=head;
for(int i=0;i<word.length();++i)
{
if(current->child[((int)word[i]-(int)'a')]==NULL)
return false;
current=current->child[((int)word[i]-(int)'a')];
}
return current->is_end;
}
然后实现main如下:
int main(){
node* head=NULL;
string s="abbaa";
init();
insert(s);
if(search("ab")==true) cout<<"Found"<<endl;
else cout<<"Not found"<<endl;
}
我得到以下输出:未找到
这很令人困惑,因为在字符串 s 中找到了 ab。
最后我试图理解这一行:
int letter=(int)word[i]-(int)'a';
这是否意味着我们正在获取 'a' 的 ASCII 码,然后从当前字符的 ASCII 码中减去?
谢谢