A Za, A Za, Fighting...

坚信:勤能补拙

2011字符串哈希, 统计词频(from 编程珠玑)

代码1(STL的map版本)
#include<iostream>
#include
<map>
#include
<string>

using namespace std;

int
main(
int argc, char **argv)
{
    map
<stringint> M;
    map
<stringint>::iterator j;
    
string t;
    
while(cin>>t)
        M[t]
++;

    
for(j=M.begin(); j!=M.end(); ++j)
        cout
<<j->first<<"\t"<<j->second<<endl;

    
return 0;
}


代码2(自己的Hash)
#include<stdio.h>
#include
<stdlib.h>
#include
<string.h>
#define WORD_BUF 128
#define NHASH 29989 /* prime number just bigger than needed */
#define MULT 31

struct HNode {
    
char *word;
    
int count;
    
struct HNode *next;
};
struct HNode *Hash[NHASH] = {NULL}; 

#define NODEGROUP 1000
struct HNode *nodebuf;
int nodeleft = 0;

struct HNode *
node_alloc()
{
    
if(nodeleft == 0) {
        nodebuf 
= (struct HNode *)malloc(NODEGROUP * sizeof(struct HNode));
        nodeleft 
= NODEGROUP;
    }
    
--nodeleft;
    
return (nodebuf++);
}

unsigned 
int
hash(
char *str) /* a simple implementation of string-hash, others like ELFHash */
{
    unsigned 
int ret = 0;
    
char *ptr;
    
for(ptr=str; *ptr; ++ptr)
        ret 
= ret * MULT + (*ptr);
    
return (ret % NHASH);
}

void
insert_hash(
char *word)
{
    
struct HNode *node;
    unsigned 
int h = hash(word);
    
for(node=Hash[h]; node!=NULL; node=node->next)
        
if(strcmp(node->word, word) == 0) {
            
++(node->count);
            
return;
        }
    
struct HNode *pend = node_alloc();
    pend
->word = strdup(word);
    pend
->count = 1;
    pend
->next = Hash[h];
    Hash[h] 
= pend;
}

int
main(
int argc, char **argv)
{
    
char buf[WORD_BUF];
    
while(scanf("%s", buf) != EOF) {
        insert_hash(buf);
    }

    
int i;
    
struct HNode *node;
    
for(i=0; i<NHASH; ++i) 
        
for(node=Hash[i]; node!=NULL; node=node->next) 
            printf(
"%s\t%d\n", node->word, node->count);

    
return 0;
}

posted on 2011-08-19 14:37 simplyzhao 阅读(548) 评论(0)  编辑 收藏 引用 所属分类: R_找工复习2011


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜