一、func hashStr(sep string) (uint32, uint32)
先分析下golang用得hash算法
32 bit FNV_prime = 2^24 + 2^8 + 0x93 = 16777619(詳見FNV hash算法)
// primeRK is the prime base used in Rabin-Karp algorithm.
const primeRK = 16777619
// hashStr returns the hash and the appropriate multiplicative
// factor for use in Rabin-Karp algorithm.
func hashStr(sep string) (uint32, uint32) {
hash := uint32(0)
for i := 0; i < len(sep); i++ {
//hash = 0 * 16777619 + sep[i]
hash = hash*primeRK + uint32(sep[i])
}
var pow, sq uint32 = 1, primeRK
for i := len(sep); i > 0; i >>= 1 {
if i&1 != 0 {
pow *= sq
}
sq *= sq
}
return hash, pow
}
核心算法是這一句(FNV Hash算法)
hash = hash*primeRK + uint32(sep[i])
后面一段, 計算出pow(后面Index函數使用),如下公式
var pow, sq uint32 = 1, primeRK
for i := len(sep); i > 0; i >>= 1 {
if i&1 != 0 {
pow *= sq
}
sq *= sq
}
二、func Index(s, sep string) int
這是golang strings包中的Index
函數函數, 查找sep字符串在s中的位置并返回(RK算法,Rabin-Karp算法)
// Index returns the index of the first instance of sep in s, or -1 if sep is not present in s.
func Index(s, sep string) int {
//查找字符串的長度
n := len(sep)
switch {
//長度 == 0, return 0
case n == 0:
return 0
//長度 == 1,調用另外一個函數
case n == 1:
return IndexByte(s, sep[0])
//長度 == s字符串的長度相等,比較兩個字符串是否相等
case n == len(s):
if sep == s {
return 0
}
return -1
case n > len(s):
return -1
}
// Rabin-Karp search
hashsep, pow := hashStr(sep)
var h uint32
for i := 0; i < n; i++ {
h = h*primeRK + uint32(s[i])
}
if h == hashsep && s[:n] == sep {
return 0
}
for i := n; i < len(s); {
h *= primeRK
h += uint32(s[i])
h -= pow * uint32(s[i-n])
i++
if h == hashsep && s[i-n:i] == sep {
return i - n
}
}
return -1
}
常規思路(sep是關鍵詞,s是源字符串)
- 對要查找的字符串sep進行hash,此處hash值是uint32類型
- 在源字符串s中,從頭取len(sep)長度,也進行hash
- 比較兩次hash值是否一致,一致,返回index
例如在“abcdefgh”中查找“fg”的位置
- 對“fg” hash,得到hashsep
- for循環,依次取2位(len("fg")),比如第一次取,“ab”, 第二次取“bc”, 第三次取“cd”..., 進行hash,得到hashsep1
- 比較hashsep和hashsep1是否相等
golang源碼中,使用的算法如下
- 對要查找的字符串sep進行hash,得到hashsep, 此處hashsep值是uint32類型
- 在s頭部取len(sep)的字符串,進行hash,直接與上步產生的hashsep比較,相等則已經找到
- 根據上步的hashsep計算出下次需要的hashsep
例如:
在“abcdefgh”中查找“fg”的位置
- 對“fg” hash,得到hashsep
hashsep, pow := hashStr(sep)
- 取出“ab”進行hash,得到hash值,與hashsep比較
var h uint32
for i := 0; i < n; i++ {
h = h*primeRK + uint32(s[i])
}
if h == hashsep && s[:n] == sep {
return 0
}
- 根據“ab”的hash值,計算出“bc”的hash值(這一步很巧妙)
for i := n; i < len(s); {
h *= primeRK
h += uint32(s[i])
h -= pow * uint32(s[i-n])
i++
if h == hashsep && s[i-n:i] == sep {
return i - n
}
}
分析一下怎么根據“ab”的hash值,計算出“bc”的hash值
還以“abcdefg”中查找“ef”為例
- 計算hash["ab"] (表示“ab”的hash值)
-
計算hash["bc"]
- 從hash["ab"]計算出hash["bc"]
可以用多位字符串試一試,我這里只用兩位
對比一下剛才這段代碼
for i := n; i < len(s); {
h *= primeRK
h += uint32(s[i])
h -= pow * uint32(s[i-n])
i++
if h == hashsep && s[i-n:i] == sep {
return i - n
}
}
func hashStr(sep string) (uint32, uint32)
函數返回的pow就是用來計算下一個組合的hash值的h -= pow * uint32(s[i-n])