参考:http://www.cnblogs.com/tanky_woo/archive/2010/09/24/1833717.html
代码:
#include<iostream>
#include<cstring>
using namespace std;
const int MAX=26;
struct Trie {
Trie *next[MAX];
int v; //根据需要变化,1代表无此单词,-1代表有此单词
};
Trie *root=new Trie;
void createTrie(char *str){
int len = strlen(str);
Trie *p = root, *q;
for(int i=0; i<len; ++i){
int id = str[i]-'a';
if(p->next[id] == NULL){
// q = (Trie *)malloc(sizeof(Trie));
q = new Trie;
q->v = 1; //初始v==1
for(int j=0; j<MAX; ++j)
q->next[j] = NULL;
p->next[id] = q;
}
p = p->next[id];
}
p->v = -1; //若为结尾,则将v改成-1表示
}
int findTrie(char *str){
int len = strlen(str);
Trie *p = root;
for(int i=0; i<len; ++i){
int id = str[i]-'a';
p = p->next[id];
if(p == NULL) //若为空集,表示不存以此为前缀的串
return 0;
if(p->v == -1) //字符集中已有串是此串的前缀
return 1;
}
return 2; //此串是字符集中某串的前缀
}
int deleteTrie(Trie* T){
int i;
if(T==NULL)
return 0;
for(i=0;i<MAX;i++){
if(T->next[i]!=NULL)
deleteTrie(T->next[i]);
}
//free(T);
delete(T);
return 0;
}
int main(){
char str[20];
int i;
for(i=0;i<MAX;i++)
root->next[i]=NULL;
cout<<"输入串1:";
cin>>str;
createTrie(str);
cout<<"输入串2:";
cin>>str;
cout<<findTrie(str)<<endl;
return 0;
}