词频统计问题

利用二叉排序树解决词频统计问题

【易错点】

1.在插入之前要判断是否为单词

2.root和count都要初始化

【代码】

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define maxSize 100

typedef struct BTNode
{
	char data[maxSize];
	struct BTNode* lchild, *rchld;
	int count;//单词在字符串中出现的次数
}BTNode;

//二叉排序树插入算法
BTNode* Insert(BTNode* root, char word[])
{
	if (root == NULL)
	{
		root = (BTNode*)malloc(sizeof(BTNode));
		root->lchild = root->rchld = NULL;
		root->count = 1;
		strcpy(root->data, word);
	}
	else if (strcmp(root->data, word) > 0)
	{
		root->lchild = Insert(root->lchild, word);
	}
	else if (strcmp(root->data, word) == 0)
	{
		(root->count)++;
	}
	else
	{
		root->rchld = Insert(root->rchld, word);
	}

	return root;
}

//前序遍历输出统计的单词次数
void pre(BTNode*bt)
{
	if (bt)
	{
		printf("%s:%d\n", bt->data, bt->count);
		pre(bt->lchild);
		pre(bt->rchld);
	}
}


//判断是否为字母,是就返回1,不是返回0
int IsAlpha(char ch)
{
	if ((ch >= 'A'&& ch <= 'Z') || (ch >= 'a'&&ch <= 'z'))
		return 1;
	return 0;
}

int main()
{
	//输入字符串
	char s[10000];
	char c;
	int i;
	BTNode* root;
	root = NULL;
	
	i = 0;
	while ((c = getchar()) != '\n')
	{
		s[i++] = c;
	}
	s[i] = '\0';

	//构建二叉排序树
	char word[maxSize];
	int j;

	i = 0;
	while (s[i] != '\0')
	{
		j = 0;
		//判断是否为单词
		while (IsAlpha(s[i]))
		{
			word[j] = s[i];
			j++;
			i++;
		}
		word[j] = '\0';

		//如果是单词则插入
		if (word[0] != '\0')
		{
			root = Insert(root, word);
		}

		//不是单词则跳过
		while (!IsAlpha(s[i]))
		{
			if (s[i] == '\0')
				break;
			i++;
		}
	}
	
	pre(root);

	return 0;
}

【测试】

利用自定义结构体解决

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值