数据结构——哈希表

哈希表

哈希表:就是把一堆数据映射到从零到n
映射的函数就是哈希函数,一般是取模

二大类:

  • 开放寻址发
  • 拉链法

在这里插入图片描述

在这里插入图片描述

题目

题解

维护一个集合,支持如下几种操作:
“I x”,插入一个数x;
“Q x”,询问数x是否在集合中出现过;
现在要进行N次操作,对于每个询问操作输出对应的结果。
1≤N≤105
−109≤x≤109
109 太大了,开一个这样的数组浪费,所以可以用的哈希表

在这里插入图片描述

class MyHashMap{
	int N = 100003; //为什么是100003,100003是一个10w后的第一个质数
	int[] h = new int[N];
	int[] e = new int[N];
	int[] ne = new int[N];
	int idx=0;
	
	private int hash(int x){
		return (x%N+N)%N;
	}
	
	public void insert(int x){
		e[idx] = x;
		int hash = hash(x);
		ne[idx] = h[hash];
		h[hash] = idx++;
	}
	
	public boolean find(int x){
		int hash = hash(x);
		for(int i = h[hash];i>=0;i=ne[i]){
			if(e[i]==x)return true;
			else if(i==0) return false;
		}
		return false;
	}
}

字符串哈希

在这里插入图片描述

第一步:前缀哈希
在这里插入图片描述
在这里插入图片描述

第二步 利用前缀哈希,计算任意字串哈希
在这里插入图片描述
在这里插入图片描述

题目

题解

给定一个长度为n的字符串,再给定m个询问,每个询问包含四个整数l1,r1,l2,r2,请你判断[l1,r1]和[l2,r2]这两个区间所包含的字符串子串是否完全相同。
字符串中只包含大小写英文字母和数字。

在这里插入图片描述

package Chapter2;
/**
 * P841 字符串哈希
 * @author vccyb
 *
 */
import java.io.*;
public class P841 {
	
	static final int N = 100010;
	static long[] p = new long[N];
	static long[] h = new long[N];
	static int b = 131;
	static long mod = Long.MAX_VALUE;
	
	//字符串前缀哈希
	static void init(String s){
		p[0] = 1;
		char[] arr = s.toCharArray();
		for(int i=1;i<=arr.length;i++){
			h[i] = (h[i-1]*b+arr[i-1])%mod;
			p[i] = p[i-1]*b;
		}
	}
	
	static long query(int l, int r){
		return h[r] - h[l-1] *p[r-l+1];
	}
	public static void main(String[] args) throws IOException {
        BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
        String[] line = in.readLine().split(" ");
        int n=Integer.parseInt(line[0]);
        int m=Integer.parseInt(line[1]);
        String s = in.readLine();
        init(s);
        
        while(m-->0){
            String[] arr=in.readLine().split(" ");
            int l1 = Integer.parseInt(arr[0]);
            int r1 = Integer.parseInt(arr[1]);
            int l2 = Integer.parseInt(arr[2]);
            int r2 = Integer.parseInt(arr[3]);

            if(query(l1, r1)==query(l2, r2)){
                System.out.println("Yes");
            }
            else{
                System.out.println("No");
            }
        }


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值