Trie

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年百度之星的第一题等等。 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值