[算法设计]hash

hash

基本问题
image.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <cstdio>
#define MAXSIZE 1000
void HashInt(int a[], int b[]) {
bool c[MAXSIZE] = { false };
int m, n;
printf("a,b数组元素的个数:");
scanf("%d%d", &m, &n);
for (int i = 0; i < m; ++i) {
int tmp;
scanf("%d", &tmp);
a[i] = tmp;
c[tmp] = true;
}//空间换取时间
for (int j = 0; j < n; ++j) {
int tmp;
scanf("%d", &tmp);
b[j] = tmp;
if (c[tmp]) printf("%d在a中存在",tmp);
}

}

字符串hash

大写字符hash核心代码:

1
2
3
for(int i=0; i<len(s): ++i){
id = id*26 + (s[i]- 'A')
}

大小写字母均hash

1
2
3
4
5
6
7
for(int i=0; i<len(s): ++i){
if(s[i]>'A' && s[i]<'Z')
id = id*26 + (s[i]- 'A')
else(s[i]>'a' && s[i]<'z')
id = id*52 + (s[i]-'a') + 26
}