哈希应用——宝石计数

mac2022-06-30  21

注意: 1.本博客仅供参考交流使用,请读者务必自行实践,切勿生搬硬套 2.由于笔者水平有限,若文中有错误或者可以改进之处,欢迎在评论区指出

题目 Description

你是一位矿主,收集了一批石头,这批石头中有宝石也有普通的石头,给定一个宝石的列表,计算这批石头中的宝石数目。要求使用size不超过10的hash表来完成此项任务。特殊字符(!@#$%^&*)和字母均可使用唯一的ascii码表示,请同学们查阅ascii码的原理,表示方式以及与int类型的相互转换方式。使用线性探测法解决冲突。

Input 分别输入两行string数据。第一行数据是宝石的种类(第一行数据不会重复),第二行数据是你所拥有的所有石头。PS:注意区分大小写,大写和小写代表不同种类的宝石。

Output 宝石数量M。

Sample Input 1

bKA bBBBaAAKKzzmmkkk Sample Output 1

5 Sample Input 2

KL@ kkll&&&&OKMMMMML@ Sample Output 2

3

由于本题比较简单,不多说,可参考我另外一篇相关文章 哈希应用—求同一条直线上的点的数量 转化为ascii用ord函数即可

Coding:

from typing import List, Any class HashTable(object): def __init__(self, size: object = 10) -> object: self.size = size self._table = [[None, -1]] * size def find_key(self, key): index = key % self.size while self._table[index][0] is not None and key != self._table[index][0]: index = (index + 1) % self.size return index def append(self, key): index = self.find_key(key) if index is not None: self._table[index] = [key, self._table[index][1] + 1] return True else: return False def check_key(self, key): for j, item in enumerate(self._table): if item[0] is not None and item[0] == key: item[1] += 1 return True return False h = HashTable() count = 0 n = list(map(ord, input())) for i in range(len(n)): h.append(n[i]) m = list(map(ord, input())) for i in range(len(m)): if h.check_key(m[i]): count += 1 print(count)
最新回复(0)