Trie:是一种针对可变长度关键字的索引结构,除了度d>=2外,它的每一层分支不是靠整个关键字的值来确定,而是由关键字的一个分量来确定。当然这也注定了,其关键字的每一个候选分量必须属于某个有限集合,感觉上有点象RadixSort的意思。这就是问什么Trie被称为字典数的原因了。
以字典为例,定义如下Trie:
const int num_chars = 26;
const int word_len=24;
struct Trie_node {
char* data;
Trie_node* branch[num_chars];
Trie_node(){
data = NULL;
for (int i=0; i<num_chars; ++i) branch[i] = NULL;
};
};
class Trie {
public:
Trie():root(NULL){};
bool trie_search(const char* word, char* entry ) const;
bool insert(char word[word_len], char entry[word_len]);
//bool del(char word[word_len]);实现参考insert()
protected:
Trie_node* root;
};
bool Trie::trie_search(const char* word, char* entry ) const {
int position = 0;
int code;
Trie_node *location = root;
while( location!=NULL && *word!=0 ) {
code = (int)(*word-’a’);
location = location->branch[code];
position++;
word++;
}
if ( location != NULL && location->data != NULL ) {
strcpy(entry,location->data);
return true;
}
else return false;
}
bool Trie::insert(char word[word_len], char entry[word_len]) {
int position = 0;
if ( root == NULL ) root = new Trie_node;
int code;
Trie_node *location = root;
while( location!=NULL && *word!=0 ) {
if (*word>=‘a’ && *word<=‘z’) code=(int)(*word-’a’);
if( location->branch[code] == NULL ) location->branch[code] = new Trie_node;
location = location->branch[code];
position++;
word++;
}
if (location->data != NULL) return false;
else {
location->data = new char[strlen(entry)+1];
strcpy(location->data, entry);
}
return true;
}
经典的例子有http://acm.pku.edu.cn/JudgeOnline/problem?id=2503
以及2006年百度之星的第一题等等。