UVa10391-- Compound Words(字符串hash)

题目大意:给出一个字典,找出所有复合词,即该单词由字典里的两个单词连接而成。


分析:字符串hash。首先,将字符串压缩成一个整数,这个整数我们就称之为hash。当然,不可能每一个字符串都对应一个不同的整数,所以,我们用类似邻接表的方法做出一个哈希表。然后,又每个单词可以拆分成两个单词,我们就可以通过hash值,在几乎常数的时间内判断单词是否在字典里。


代码:

#include <cstdio>
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;

const int maxn =1000003;

int head[maxn], next[maxn];     //数组形式的hash表
string s[maxn];
int cnt;

void init() {
    for(int i = 0; i < maxn; i++)
        head[i] = next[i] = -1;
    cnt = 0;
}

int gethash(string str) {
    int sum = 0;
    int len = str.length();
    for(int i = 0; i < len; i++)
        sum = (sum << 5) + str[i];
    return (sum&0x7fffffff) % maxn;
}

void add(string str) {
    int c = gethash(str);
    s[cnt] = str;
    next[cnt] = head[c];
    head[c] = cnt++;
}

bool exist(string str) {
    int c= gethash(str);
    for(int i = head[c]; i != -1; i = next[i])
        if(s[i] == str) return true;
    return false;
}

int main() {
    string str;
    init();
    while(cin >> str) add(str);
    for(int i = 0; i <cnt; i++) {
        int len = s[i].length();
        for(int j = 1; j < len; j++) {
            string s1 = s[i].substr(0, j);
            string s2 = s[i].substr(j, len-j);
            if(exist(s1) && exist(s2)) {
                cout << s[i] << endl;
                break;
            }
        }
    }
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值