字典树的应用 单词意义查找-C语言实现

/*
字典树应用,快速单词查找 
*/

const int M = 1000000;
char word[1000000][11];
int wp; // 单词列表的下标 
struct node{
	int next[26];
	int value;
	bool end;
} tree[M]; // 可用节点数组,相当于内存池 
int pi = 1; // 代表空闲的节点位置 
void init(){
	memset(tree,0,sizeof(tree));
	pi = 1; // 头节点占用0,空闲节点从1开始 
	wp = 0;
}
void insert(char * keyword,int value){
	int index,p,i; // p代表当前的节点,开始为根节点 
	for(i=p=0;keyword[i];i++){
		index = keyword[i] - 'a';
		if(tree[p].next[index] == 0)
			tree[p].next[index] = pi++;
		p = tree[p].next[index]; 
	}
	tree[p].value = value;
	tree[p].end = 1;
}
bool query(char * keyword, int &value){
	int index,p,i;
	for(i=p=0;keyword[i];i++){
		index = keyword[i] - 'a';		
		if(tree[p].next[index] == 0)
			return 0;
		p = tree[p].next[index];
	}
	if(tree[p].end){
		value = tree[p].value;
		return 1; 
	}
	return 0;
}
int main(){
	char s1[15],s2[15],s[30];
	int i,value;
	while(gets(s)){
		if(!strlen(s))
			break;
		for(i=0;i<strlen(s);i++){
			if(s[i]==' ')
				break;
		}
		strncpy(s1,s,i); // say speak ==> say
		s1[i] = 0;
		strcpy(s2,s+i+1);
		strcpy(word[wp],s1); // 单词数组(二维) 
		insert(s2,wp++); // 含义插入字典树,应用时根据含义找单词,用下标wp进行关联 
	}
	while(scanf("%s",s)!=EOF){
		if(query(s,value))
			cout<<word[value]<<endl;
		else
			cout<<"no the word"<<endl;
		}
}

实现根据单词快速找到对应的解释


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是用C语言实现字典树的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_CHILDREN 26 struct TrieNode { int count; // 记录单词出现次数 struct TrieNode* children[MAX_CHILDREN]; }; struct Trie { struct TrieNode* root; }; struct TrieNode* create_node() { struct TrieNode* node = (struct TrieNode*)malloc(sizeof(struct TrieNode)); node->count = 0; for (int i = 0; i < MAX_CHILDREN; i++) { node->children[i] = NULL; } return node; } void insert(struct Trie* trie, char* word) { struct TrieNode* p = trie->root; for (int i = 0; i < strlen(word); i++) { int index = word[i] - 'a'; if (p->children[index] == NULL) { p->children[index] = create_node(); } p = p->children[index]; } p->count++; } int search(struct Trie* trie, char* word) { struct TrieNode* p = trie->root; for (int i = 0; i < strlen(word); i++) { int index = word[i] - 'a'; if (p->children[index] == NULL) { return 0; } p = p->children[index]; } return p->count; } int main() { struct Trie trie; trie.root = create_node(); insert(&trie, "apple"); insert(&trie, "app"); insert(&trie, "application"); int count = search(&trie, "app"); printf("单词 app 出现的次数为:%d\n", count); return 0; } ``` 以上代码中,`create_node` 函数用于创建字典树节点,`insert` 函数用于向字典树中插入单词,`search` 函数用于在字典树查找单词出现的次数。`main` 函数则测试了该字典树在插入单词 `"apple"`、`"app"`、`"application"` 后查找单词 `"app"` 出现的次数的结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值