数据结构与算法题目集7-43——字符串关键字的散列映射

我的数据结构与算法题目集代码仓:https://github.com/617076674/Data-structure-and-algorithm-topic-set

原题链接:https://pintia.cn/problem-sets/15/problems/890

题目描述:

知识点:哈希表

思路:字符串哈希

数据结构与算法题目集7-42——整型关键字的散列映射中的注意点一样,有可能该字符串已经在哈希表中,这时候我们不需要插入,只需输出其在哈希表中的位置即可。

C++代码:

#include<iostream>
#include<cstring>

using namespace std;

int changeToInt(char* str);

int main() {
	int N, P;
	scanf("%d %d", &N, &P);
	char strs[P][9];
	bool filled[P];
	fill(filled, filled + P, false);
	for(int i = 0; i < N; i++){
		char input[9];
		scanf("%s", input);
		int num = changeToInt(input);
		for(int j = 0; j < P; j++){
			int index1 = (num + j * j) % P;
			if(!filled[index1] || strcmp(strs[index1], input) == 0){
				filled[index1] = true;
				strcpy(strs[index1], input);
				printf("%d", index1);
				break;
			}
			int index2 = (num - j * j) % P;
			while(index2 < 0){
				index2 += P;
			}
			if(!filled[index2] || strcmp(strs[index2], input) == 0){
				filled[index2] = true;
				strcpy(strs[index2], input);
				printf("%d", index2);
				break;
			}
		}
		if(i == N - 1){
			printf("\n");
		}else{
			printf(" ");
		}
	}
	return 0;
}

int changeToInt(char* str) {
	int result = 0;
	int len = strlen(str);
	for(int i = max(len - 3, 0); i < len; i++) {
		result = result * 32 + str[i] - 'A';
	}
	return result;
}

C++解题报告:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值