Rabin-karp演算法實現 字串匹配
阿新 • • 發佈:2018-11-05
// RabinKarp演算法實現
// RabinKarp演算法實現 const primeRK = 16777619 func hashStr(seq string) (uint32, uint32) { hash := uint32(0) for _, value := range seq { hash = hash * primeRK + uint32(value) } var pow, sq uint32 = 1, primeRK for i := len(seq); i > 0; i >>= 1 { if i & 1 != 0 { pow *= sq } sq *= sq } return hash, pow } func rabinKarp(s, substr string) int { hashss, pow := hashStr(substr) n := len(substr) var h uint32 for i := 0; i < n; i++ { h = h*primeRK + uint32(s[i]) } if h == hashss && s[:n] == substr { return 0 } for i := n; i < len(s); { h *= primeRK h += uint32(s[i]) h -= pow * uint32(s[i-n]) i++ if h == hashss && s[i-n:i] == substr { return i - n } } return -1 } func strStr(haystack string, needle string) int { n := len(needle) switch { case n == 0: return 0 case n == len(haystack): if haystack == needle { return 0 } return -1 case n > len(haystack): return -1 } return rabinKarp(haystack, needle) }