暴雪公司有個經典的字符串的hash公式
先提一個簡單的問題,假如有一個龐大的字符串數組,然后給你一個單獨的字符串,讓你從這個數組中查找是否有這個字符串並找到它,你會怎么做?
有一個方法最簡單,老老實實從頭查到尾,一個一個比較,直到找到為止,我想只要學過程序設計的人都能把這樣一個程序作出來,但要是有程序員把這樣的程序交給用戶,我只能用無語來評價,或許它真的能工作,但也只能如此了。
最合適的算法自然是使用HashTable(哈希表),先介紹介紹其中的基本知識,所謂Hash,一般是一個整數,通過某種算法,可以把一個字符串"壓縮" 成一個整數,這個數稱為Hash,當然,無論如何,一個32位整數是無法對應回一個字符串的,但在程序中,兩個字符串計算出的Hash值相等的可能非常小,下面看看在MPQ中的Hash算法
1 unsigned long HashString(char *lpszFileName, unsigned long dwHashType) 2 { 3 unsigned char *key = (unsigned char *)lpszFileName; 4 unsigned long seed1 = 0x7FED7FED, seed2 = 0xEEEEEEEE; 5 int ch; 6 while(*key != 0) 7 { 8 ch = toupper(*key++ ); 9 seed1 = cryptTable[(dwHashType << 8) + ch] ^ (seed1 + seed2); 10 seed2 = ch + seed1 + seed2 + (seed2 << 5) + 3; 11 } 12 return seed1; 13 }
Blizzard的這個算法是非常高效的,被稱為"One-Way Hash",舉個例子,字符串"unitneutralacritter.grp"通過這個算法得到的結果是0xA26067F3。
是不是把第一個算法改進一下,改成逐個比較字符串的Hash值就可以了呢,答案是,遠遠不夠,要想得到最快的算法,就不能進行逐個的比較,通常是構造一個哈希表(Hash Table)來解決問題,哈希表是一個大數組,這個數組的容量根據程序的要求來定義,例如1024,每一個Hash值通過取模運算 (mod)對應到數組中的一個位置,這樣,只要比較這個字符串的哈希值對應的位置又沒有被占用,就可以得到最后的結果了,想想這是什么速度?是的,是最快的O(1),現在仔細看看這個算法吧
1 int GetHashTablePos(char *lpszString, SOMESTRUCTURE *lpTable, int nTableSize) 2 { 3 int nHash = HashString(lpszString), nHashPos = nHash % nTableSize; 4 if (lpTable[nHashPos].bExists && !strcmp(lpTable[nHashPos].pString, lpszString)) 5 return nHashPos; 6 else 7 return -1; //Error value 8 }
看到此,我想大家都在想一個很嚴重的問題:"假如兩個字符串在哈希表中對應的位置相同怎么辦?",究竟一個數組容量是有限的,這種可能性很大。解決該問題的方法很多,我首先想到的就是用"鏈表",感謝大學里學的數據結構教會了這個百試百靈的法寶,我碰到的很多算法都可以轉化成鏈表來解決,只要在哈希表的每個入口掛一個鏈表,保存所有對應的字符串就OK了。
事情到此似乎有了完美的結局,假如是把問題獨自交給我解決,此時我可能就要開始定義數據結構然后寫代碼了。然而Blizzard的程序員使用的方法則是更精妙的方法。基本原理就是:他們在哈希表中不是用一個哈希值而是用三個哈希值來校驗字符串。
中國有句古話"再一再二不能再三再四",看來Blizzard也深得此話的精髓,假如說兩個不同的字符串經過一個哈希算法得到的入口點一致有可能,但用三個不同的哈希算法算出的入口點都一致,那幾乎可以肯定是不可能的事了,這個幾率是1:18889465931478580854784,大概是10的 22.3次方分之一,對一個游戲程序來說足夠安全了。
現在再回到數據結構上,Blizzard使用的哈希表沒有使用鏈表,而采用"順延"的方式來解決問題,看看這個算法:
1 int GetHashTablePos(char *lpszString, MPQHASHTABLE *lpTable, int nTableSize) 2 { 3 const int HASH_OFFSET = 0, HASH_A = 1, HASH_B = 2; 4 int nHash = HashString(lpszString, HASH_OFFSET); 5 int nHashA = HashString(lpszString, HASH_A); 6 int nHashB = HashString(lpszString, HASH_B); 7 int nHashStart = nHash % nTableSize, nHashPos = nHashStart; 8 while (lpTable[nHashPos].bExists) 9 { 10 if (lpTable[nHashPos].nHashA == nHashA && lpTable[nHashPos].nHashB == nHashB) 11 return nHashPos; 12 else 13 nHashPos = (nHashPos + 1) % nTableSize; 14 if (nHashPos == nHashStart) 15 break; 16 } 17 return -1; //Error value 18 }
1. 計算出字符串的三個哈希值(一個用來確定位置,另外兩個用來校驗)
2. 察看哈希表中的這個位置
3. 哈希表中這個位置為空嗎?假如為空,則肯定該字符串不存在,返回
4. 假如存在,則檢查其他兩個哈希值是否也匹配,假如匹配,則表示找到了該字符串,返回
5. 移到下一個位置,假如已經越界,則表示沒有找到,返回
6. 看看是不是又回到了原來的位置,假如是,則返回沒找到
7. 回到3
怎么樣,很簡單的算法吧,但確實是天才的idea, 其實最優秀的算法往往是簡單有效的算法。
附上完整的算法代碼:
1 /*********************************StringHash.h*********************************/ 2 3 #pragma once 4 5 #define MAXTABLELEN 1024 // 默認哈希索引表大小 6 ////////////////////////////////////////////////////////////////////////// 7 // 哈希索引表定義 8 typedef struct _HASHTABLE 9 { 10 long nHashA; 11 long nHashB; 12 bool bExists; 13 }HASHTABLE, *PHASHTABLE ; 14 15 class StringHash 16 { 17 public: 18 StringHash(const long nTableLength = MAXTABLELEN); 19 ~StringHash(void); 20 private: 21 unsigned long cryptTable[0x500]; 22 unsigned long m_tablelength; // 哈希索引表長度 23 HASHTABLE *m_HashIndexTable; 24 private: 25 void InitCryptTable(); // 對哈希索引表預處理 26 unsigned long HashString(const string& lpszString, unsigned long dwHashType); // 求取哈希值 27 public: 28 bool Hash(string url); 29 unsigned long Hashed(string url); // 檢測url是否被hash過 30 }; 31 32 33 34 /*********************************StringHash.cpp*********************************/ 35 36 #include "StdAfx.h" 37 #include "StringHash.h" 38 39 StringHash::StringHash(const long nTableLength /*= MAXTABLELEN*/) 40 { 41 InitCryptTable(); 42 m_tablelength = nTableLength; 43 //初始化hash表 44 m_HashIndexTable = new HASHTABLE[nTableLength]; 45 for ( int i = 0; i < nTableLength; i++ ) 46 { 47 m_HashIndexTable[i].nHashA = -1; 48 m_HashIndexTable[i].nHashB = -1; 49 m_HashIndexTable[i].bExists = false; 50 } 51 } 52 53 StringHash::~StringHash(void) 54 { 55 //清理內存 56 if ( NULL != m_HashIndexTable ) 57 { 58 delete []m_HashIndexTable; 59 m_HashIndexTable = NULL; 60 m_tablelength = 0; 61 } 62 } 63 64 /************************************************************************/ 65 /*函數名:InitCryptTable 66 /*功 能:對哈希索引表預處理 67 /*返回值:無 68 /************************************************************************/ 69 void StringHash::InitCryptTable() 70 { 71 unsigned long seed = 0x00100001, index1 = 0, index2 = 0, i; 72 73 for( index1 = 0; index1 < 0x100; index1++ ) 74 { 75 for( index2 = index1, i = 0; i < 5; i++, index2 += 0x100 ) 76 { 77 unsigned long temp1, temp2; 78 seed = (seed * 125 + 3) % 0x2AAAAB; 79 temp1 = (seed & 0xFFFF) << 0x10; 80 seed = (seed * 125 + 3) % 0x2AAAAB; 81 temp2 = (seed & 0xFFFF); 82 cryptTable[index2] = ( temp1 | temp2 ); 83 } 84 } 85 } 86 87 /************************************************************************/ 88 /*函數名:HashString 89 /*功 能:求取哈希值 90 /*返回值:返回hash值 91 /************************************************************************/ 92 unsigned long StringHash::HashString(const string& lpszString, unsigned long dwHashType) 93 { 94 unsigned char *key = (unsigned char *)(const_cast<char*>(lpszString.c_str())); 95 unsigned long seed1 = 0x7FED7FED, seed2 = 0xEEEEEEEE; 96 int ch; 97 98 while(*key != 0) 99 { 100 ch = toupper(*key++); 101 102 seed1 = cryptTable[(dwHashType << 8) + ch] ^ (seed1 + seed2); 103 seed2 = ch + seed1 + seed2 + (seed2 << 5) + 3; 104 } 105 return seed1; 106 } 107 108 /************************************************************************/ 109 /*函數名:Hashed 110 /*功 能:檢測一個字符串是否被hash過 111 /*返回值:如果存在,返回位置;否則,返回-1 112 /************************************************************************/ 113 unsigned long StringHash::Hashed(string lpszString) 114 115 { 116 const unsigned long HASH_OFFSET = 0, HASH_A = 1, HASH_B = 2; 117 //不同的字符串三次hash還會碰撞的幾率無限接近於不可能 118 unsigned long nHash = HashString(lpszString, HASH_OFFSET); 119 unsigned long nHashA = HashString(lpszString, HASH_A); 120 unsigned long nHashB = HashString(lpszString, HASH_B); 121 unsigned long nHashStart = nHash % m_tablelength, 122 nHashPos = nHashStart; 123 124 while ( m_HashIndexTable[nHashPos].bExists) 125 { 126 if (m_HashIndexTable[nHashPos].nHashA == nHashA && m_HashIndexTable[nHashPos].nHashB == nHashB) 127 return nHashPos; 128 else 129 nHashPos = (nHashPos + 1) % m_tablelength; 130 131 if (nHashPos == nHashStart) 132 break; 133 } 134 135 return -1; //沒有找到 136 } 137 138 /************************************************************************/ 139 /*函數名:Hash 140 /*功 能:hash一個字符串 141 /*返回值:成功,返回true;失敗,返回false 142 /************************************************************************/ 143 bool StringHash::Hash(string lpszString) 144 { 145 const unsigned long HASH_OFFSET = 0, HASH_A = 1, HASH_B = 2; 146 unsigned long nHash = HashString(lpszString, HASH_OFFSET); 147 unsigned long nHashA = HashString(lpszString, HASH_A); 148 unsigned long nHashB = HashString(lpszString, HASH_B); 149 unsigned long nHashStart = nHash % m_tablelength, 150 nHashPos = nHashStart; 151 152 while ( m_HashIndexTable[nHashPos].bExists) 153 { 154 nHashPos = (nHashPos + 1) % m_tablelength; 155 if (nHashPos == nHashStart) //一個輪回 156 { 157 //hash表中沒有空余的位置了,無法完成hash 158 return false; 159 } 160 } 161 m_HashIndexTable[nHashPos].bExists = true; 162 m_HashIndexTable[nHashPos].nHashA = nHashA; 163 m_HashIndexTable[nHashPos].nHashB = nHashB; 164 165 return true; 166 }