hdu 1075(hash)

字符串哈希与拉链法解决冲突的练手题
本文介绍了一道使用字符串哈希和拉链法解决冲突的编程练习题,通过实例演示了如何高效地进行字符串匹配与查找。
//字符串hash练手题,采用拉链式解决冲突 
#include <cstdio>
#include <cstring>
#include <iostream>

using namespace std;

const int M = 43853;//hash表大小 

struct node {//节点 
    char str1[11];
    char str2[11];
    node *next; 
};

struct hashTable {//hash表 
    node *link;
}hash[M];

char text[3005];
char str1[11], str2[11], ch[11], ans[11];

void init() {//初始化 
    for (int i=0; i<M; ++i) hash[i].link = NULL;
    return ;
}

unsigned int BKDRHash(char * str) {//hash
    unsigned int seed = 131;
    unsigned int hash = 0;
    while (*str) hash = hash * seed + (*str++);
    return hash & 0x7FFFFFFF;
}

void insert(char *str1, char *str2) {//插入 
    int k = BKDRHash(str1) % M;
    node *p = new node();
    strcpy(p->str1, str1);
    strcpy(p->str2, str2);
    p->next = hash[k].link;
    hash[k].link = p;
    return ;
}

int find(char *str) { //查找 
    int k = BKDRHash(str) % M;
    node *p = hash[k].link;
    while (p) {
        if (!strcmp(p->str1, str)) {
            strcpy(ans, p->str2);
            return 1;  //找到 
        }
        p = p->next; 
    }
    return 0; // 没找到 
}

int main() {
    init();
    scanf ("%s", str1);
    while (scanf("%s", str1), strcmp(str1, "END")!=0) {
        scanf ("%s", str2);
        insert(str2, str1);
    }
    scanf ("%s", str1);
    getchar();
    while (gets(text), strcmp(text, "END")!=0) {
        int l = strlen(text);
        for (int i=0; i<l;) {
            int k = 0;
            if (text[i]>='a' && text[i]<='z') {
                int j = i;
                while (text[j]>='a' && text[j]<='z' && j<l) ch[k++] = text[j++];
                i = j;
                ch[k] = '\0';
                if (find(ch)) printf ("%s", ans);
                else printf ("%s", ch);
            }
            else printf ("%c", text[i++]);
        }
        puts("");
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/try86/archive/2012/04/09/2439341.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值