UVA10391- Compound Words

题意:找出一连串的字符串中,是否存在两个字符串相组合的字符串出现在所给的字符串中,如果有的话,将组合的那个字符串输出

思路:利用哈希函数,将每个单词分为两个部分,都存在哈希表中,搜索是否两个部分都存在,如果有的话,输出

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define MAXN 120003
using namespace std;
typedef char Word[50];

const int HashSize = 120100;
Word word[MAXN];
int N, head[HashSize], next[HashSize];

void init_lookup_table() {
    memset(head, 0, sizeof(head));
}

int hash(char *str) {
    int hash = 0;
    while (*str) 
        hash = hash * 10 + (*str++);
    return (hash & 0x7FFFFFFF) % HashSize;
}

int add_hash(int s) {
    int h = hash(word[s]);
    int u = head[h];
    next[s] = head[h];
    head[h] = s;
    return 1;
}

int search(char *s) {
    int h = hash(s);
    int u = head[h];
    while (u) {
        if (strcmp(word[u], s) == 0) 
            return u; 
        u = next[u];
    }
    return 0;
}

int main() {
    Word str;
    N = 1;
    init_lookup_table();
    while (gets(word[N])) {
        if (word[N][0] == '\0')
            break;
        add_hash(N);
        N++; 
    }
    for (int i = 1; i < N; i++)
        if (word[i][1]) {
            for (int j = 0; j < strlen(word[i]) - 1; j++) {
                strcpy(str, word[i]); 
                str[j + 1] = '\0';
                if (search(str) && search(word[i] + j + 1)) {
                    puts(word[i]); 
                    break;
                }
            }    
        }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值