哈希表
哈希表:就是把一堆数据映射到从零到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");
}
}
}
}