Lecture 9: Hashing II: Table Doubling,Karp-Rabin python
散列表應該有多大?spa
理想狀態:code
根據須要改變大小.字符串
(重散列)Rehashinghash
增加:it
散列表長度成倍增加是個好選擇.class
刪除:im
字符串匹配(String Matching)img
Simple Algorithm:co
Karp-Rabin Algorithm:
python代碼:
def karp_rabin(T, P): n = len(T) m = len(P) d = 256 q = 101 h = d ** (m - 1) % q p = 0 t = 0 for i in range(m): p = (d*p + ord(P[i])) % q t = (d*t + ord(T[i])) % q for s in range(n - m + 1): print(s,p,t) if p == t and T[s:s+m] == P: return s if s < n - m: t = ( d * ( t - ord( T[s] ) * h ) + ord( T[s + m] ) ) % q