参考大神的前缀树代码,把它简单转换了一下
前缀树主要是利用了只有26个英文字母条件下,相当于用了个26叉树
有insert,find,prefix三种方法
不过额外加了个isEnd,这个还挺巧妙的
#include <iostream>
#include <vector>
#include <cmath>
#include<unordered_set>
#include<cstring>
using namespace std;
const int N = 1000000;
struct Trie
{
bool isEnd;
Trie *next[26];
Trie(){isEnd=false;memset(next,0,sizeof(next));}
};
void insert(Trie *head,string word){
Trie *node=head;
for(char c:word){
if(!node->next[c-'a']){
node->next[c-'a']=new Trie();
}
node=node->next[c-'a'];
}
node->isEnd=true;
}
bool find(Trie *head,string word){
Trie *node =head;
for(char c:word){
if(!node->next[c-'a']){
return false;
}
node=node->next[c-'a'];
}
return node->isEnd;
}
bool prefix(Trie *head,string word){
Trie *node=head;
for(char c:word){
if(!node->next[c-'a']){
return false;
}
node=node->next[c-'a'];
}
return true;
}
int main()
{
Trie *head=new Trie();
insert(head,"qwe");
insert(head,"qwer");
insert(head,"gert");
insert(head,"zxc");
insert(head,"fasknj");
cout<<"qw有吗:"<<find(head,"qw")<<endl;
cout<<"qwe有吗"<<find(head,"qwe")<<endl;
cout<<"qwer有吗"<<find(head,"qwer")<<endl;
cout<<"qw有前缀吗"<<prefix(head,"qw")<<endl;
cout<<"qwe有前缀吗"<<prefix(head,"qwe")<<endl;
cout<<"qwer有前缀吗"<<prefix(head,"qwer")<<endl;
return 0;
}