forked from Hawstein/cracking-the-coding-interview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.h
56 lines (49 loc) · 1.18 KB
/
hash.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <cstring>
const int kWordSize = 26 + 5;
const int kNodeSize = 1200 + 5;
const int kHashSize = 10001; //大质数
struct Node{
char word[kWordSize];
Node *next;
};
Node node[kNodeSize + 1];
Node* head[kHashSize + 1];
class Hash{
public:
Hash();
unsigned int hash(const char* str);
void insert(const char* str);
bool find(const char* str);
private:
unsigned int seed;
unsigned int size;
};
Hash::Hash():seed(131),size(0){
memset(head, 0, sizeof(head));
}
unsigned int Hash::hash(const char* str){
unsigned int hash = 0;
while(*str++)
hash = hash * seed + (*str);
return (hash & 0x7FFFFFFF) % kHashSize;
}
void Hash::insert(const char* str){
unsigned int id = hash(str);
char *dst = (char*)node[size].word;
while(*dst++ = *str++);
node[size].next = head[id];
head[id] = &node[size];
++size;
}
bool Hash::find(const char* str){
unsigned int id = hash(str);
for(Node* p=head[id]; p ; p=p->next){
char *dst = (char*)p->word;
int i = 0;
while(*(str+i) && *(dst+i)==*(str+i))
++i;
if(*(str+i)=='\0' && *(dst+i)=='\0')
return true;
}
return false;
}