哈希表与字符串

预备知识:
在这里插入图片描述
1、最简单的哈希-----字符哈希

#include<stdio.h>
#include<string>
#include<stdlib.h>
using namespace std;

int main(){
	int char_map[128] = {0};//ASCⅡ码从0-127,故用数组下标做映射,最大范围至128
	string str="snaxjnjsxngdpq";
	for(int i=0;i<str.length();i++){
		char_map[str[i]]++;//统计字符串中各个字符的数量
	}
	for(int i=0;i<128;i++){
		if(char_map[i]>0)
			printf("[%c][%d]: %d\n",i,i,char_map[i]);//将字符对应的ASCⅡ码及其个数打印出来
	}
	system("pause");
	return 0;
}

在这里插入图片描述
2、哈希表排序整数

#include<stdio.h>
#include<stdlib.h>
using namespace std;

int main(){
	int random[10] = {3,456,78,43,124,789,908,78,3,124};
	int hash_map[1000] = {0};//哈希表长度需要超过最大排序数
	for(int i=0;i<10;i++){
		hash_map[random[i]]++;//统计字符串中各个字符的数量
	}
	for(int i=0;i<1000;i++){
		//从小到大查询hash表中是否出现该数字,若出现则全部打出,打印结果就为排序后de
		for(int j = 0;j < hash_map[i];j++){
			printf("%d\n",i);
		}	
	}
	system("pause");
	return 0;
}

在这里插入图片描述
问题1:如何利用哈希表实现对任意字符的映射?
在这里插入图片描述
问题2:利用上述方式映射发生冲突怎么办?
用拉链法解决
在这里插入图片描述

#include<stdio.h>
#include<stdlib.h>
#include<vector>
using namespace std;
struct ListNode{
	int val;
	ListNode *next;
	ListNode(int x):val(x),next(NULL){}
};

int hash_func(int key, int table_len){
	return key%table_len;
}

void insert(ListNode *hash_table[],ListNode *node, int table_len){
	int hash_key = hash_func(node->val,table_len);//将插入节点的值转换为hash关键值
	node->next = hash_table[hash_key];//利用头插法将新的节点插入对应哈希值位置
	hash_table[hash_key] = node;
}

bool search(ListNode *hash_table[],int value,int table_len){//查找value值
	int hash_key = hash_func(value,table_len);
	ListNode *head = hash_table[hash_key];
	while(head){
		if(head->val == value)
			return true;
		head=head->next;
	}
	return false;
}
int main(){
	const int TABLE_LEN = 11;//!!!去质数冲突会比较小
	ListNode *hash_table[TABLE_LEN]={0};
	vector<ListNode*> hash_node_vec;
	int test[8] = {14,17,404,109,9,6,7,81};//测试数组
	for(int i=0;i<8;i++) //以此生成相应节点并将测试数组的值存进数组中
		hash_node_vec.push_back(new ListNode(test[i]));
	for(int i=0;i<hash_node_vec.size();i++)
		insert(hash_table,hash_node_vec[i],TABLE_LEN);//将节点插入哈希表
	printf("Hash table:\n");
	for(int i=0;i<TABLE_LEN;i++){//打印哈希表
		printf("[%d]",i);
		ListNode* head=hash_table[i];
		while(head){
			printf("->%d",head->val);
			head=head->next;
		}
		printf("\n");
	}
	printf("\n");
	printf("Test search:\n");
	for(int i=0;i<10;i++){//查找相应的值在不在表中
		if(search(hash_table,i,TABLE_LEN))
			printf("%d is in the hash table.\n",i);
		else
			printf("%d is not in the hash table.\n",i);
	}
	system("pause");
	return 0;
}

在这里插入图片描述

一、最长回文串 LeetCode409

题目:

  • 3
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值