Trie 树实现《圣经》词频统计

Trie树又称单词查找树,Trie树,是一种树形结构,是一种哈希树的变种。典型应用是用于统计,排序和保存大量的字符串(但不仅限于字符串),所以经常被搜索引擎系统用于文本词频统计。它的优点是:利用字符串的公共前缀来减少查询时间,最大限度地减少无谓的字符串比较,查询效率比哈希树高。根节点不包含字符,除根节点外每一个节点都只包含一个字符; 从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串; 每个节点的所有子节点包含的字符都不相同。  来源:百度百科
#include<iostream>
#include<cstdio>
#include<cstring>
#define MAX 50
using namespace std;
struct node{
int realnum;
struct node *next[26];
char real[MAX];
};
typedef struct node* myNode;
class Trie{
public:
    myNode tree;
    Trie()
    {
        tree=new node;
        tree->realnum=0;
        for (int i = 0;  i<26 ; ++i)
            tree->next[i] = NULL;   
    } 
    void addnode(char*);
    void dfs(myNode);
};
void Trie::addnode(char a[])//添加结点 
{
int i,j;
myNode ptr=tree;
for(i=0;a[i]!='\0';++i)
{
    if(!ptr->next[a[i]-'a'])
    {
        ptr->next[a[i]-'a']=new node;
        ptr->next[a[i]-'a']-> realnum = 0;
        for ( j = 0;  j<26 ; ++j)
        {
            ptr->next[a[i]-'a']->next[j] = NULL;
        }
    }
    ptr =ptr->next[a[i]-'a'];
}
ptr->realnum++;
strcpy(ptr->real,a);    
}
void Trie::dfs(myNode ptr)//搜索 
{
if(ptr){
    if(ptr!=tree&&ptr->realnum !=0)
    cout<<ptr->real<<" "<<ptr->realnum <<endl;
    for(int i=0;i<26;++i)
        dfs(ptr->next[i]);
}
}
int main()
{
Trie WFC;
freopen("圣经.txt","r",stdin);
freopen("result.txt","w",stdout);
char ch,temp;
int tempNum=0;
char str[MAX];
while(cin.get(ch)){
    if(ch>='a'&&ch<='z')
        temp=ch;
    else if(ch>='A'&&ch<='Z')
        temp=ch-'A'+'a';
    else
    {
        str[tempNum]='\0';
        tempNum=0;
        WFC.addnode(str);
        continue;
    }
    str[tempNum++]=temp;    
}
WFC.dfs(WFC.tree);
return 0;
} 

我作为爱吃紫菜汤的lan小猪,就不一行一行写注释了//
效果如图:圣经中单词频率统计

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值