-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMyHashTable.java
68 lines (64 loc) · 1.65 KB
/
MyHashTable.java
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
57
58
59
60
61
62
63
64
65
66
67
68
public class MyHashTable
{
// implements the hashtable used by the InvertedPageIndex.
// It maps a word to its word-entry.
private int size;
private MyLinkedList<WordEntry>[] hashTable;
@SuppressWarnings("unchecked")
public MyHashTable()
{
size = 100000;
hashTable = new MyLinkedList[size];
}
// Create a hash function which maps a string to the index of its word-entry in the
// hashtable. The implementation of hashtable supports chaining.
private int getHashIndex(String str)
{
int n = str.length(), a = 1, code = 0;
for(int i=0;i<n;i++)
{
code = (code + str.charAt(i)*a) % size;
a = (a * 41) % size;
}
return code;
}
// This adds an entry to the hashtable: stringName(w) - > positionList(w). If no word-entry
// exists, then create a new word entry. However, if a word-entry exists,
// then merge w with the existing word-entry.
public void addPositionsForWord(WordEntry w)
{
int index = getHashIndex(w.getWord());
if(hashTable[index] == null)
{
hashTable[index] = new MyLinkedList<WordEntry>();
hashTable[index].Insert(w.Clone());
}
else
{
MyLinkedList<WordEntry>.Node tmp = hashTable[index].head;
while(tmp != null)
{
if(tmp.obj.equals(w))
{
tmp.obj.addPositions(w.getAllPositionsForThisWord());
return;
}
tmp = tmp.next;
}
hashTable[index].Insert(w.Clone());
}
}
public WordEntry searchWord(String str)
{
int index = getHashIndex(str);
if(hashTable[index] == null) return null;
MyLinkedList<WordEntry>.Node tmp = hashTable[index].head;
while(tmp != null)
{
if(tmp.obj.getWord().equals(str))
return tmp.obj;
tmp = tmp.next;
}
return null;
}
}