下面是一个使用哈希表实现的程序,可以获取字符串的第一个字符:
class HashTable:
def __init__(self):
self.table = [None] * 26
def hash_func(self, key):
# 哈希函数,将字符转换为0-25的索引
return ord(key[0].lower()) - ord('a')
def insert(self, key, value):
# 插入键值对到哈希表
index = self.hash_func(key)
self.table[index] = value
def get(self, key):
# 获取键对应的值
index = self.hash_func(key)
return self.table[index]
使用示例:
hash_table = HashTable()
hash_table.insert('apple', 'a')
hash_table.insert('banana', 'b')
hash_table.insert('cat', 'c')
print(hash_table.get('apple')) # 输出:a
print(hash_table.get('banana')) # 输出:b
print(hash_table.get('cat')) # 输出:c
这个程序使用了一个长度为26的列表作为哈希表,每个字符对应一个索引。哈希函数将字符转换为索引,然后将键值对插入到对应的索引位置。使用时,可以通过键获取对应的值。