哈希,是解决字符串(实际上是各种类)问题的重要工具,讲字符串储存读取速度降低到了线性,哈希的用法十分丰富,可以用了进行状态压缩等。
#include<string.h>
#include<stdio.h>
#include<string>
#include<vector>
using namespace std;
//这与jdk String.hashCode()的函数在足够大的数据下失配率相近
int seed = 31;
const int mod = 10007;//这里设置取模值
int hasH(string src) {//末尾字母大写规避与stl冲突
int hash = 0;
for (int i = 0; i != src.size(); ++i){
hash = seed * hash + src[i];
}
if (hash < 0) {
hash *= -1;
}
return hash % mod;
}
//下面是冲突处理,不一定有必要
const int n = 1;//点数
class Node {
public:
string str;
int next;
Node(){
next = -1;
}
};
Node node[n];
//利用前向星实现拉链法
int cnt;
int head[mod];//hash_table
void add(string s) {
if (search(s) != -1) {
return;
}
int site = hasH(s);
node[cnt].str = s;
node[cnt].next = head[site];
head[site] = cnt++;
}
int search(string s) {
int site = hasH(s);
for (int i = head[i]; i != -1; i = node[i].next) {
if (s == node[i].str) {
return i;
}
}
return -1;
}