This is a creation in Article, where the information may have evolved or changed.
The details of the algorithm can refer to the information on the Internet or data structure of the relevant materials, here directly on the code ~
In view of my skills shallow, some places may not be reasonable, the code is slightly longer, if there are improvements, please leave a message pointing, the algorithm itself tested:
Package Mainimport ("FMT") func Getnextvaluearray (sub []byte) (Next []int) {var (length int = len (sub) Middle Intcompare_left intcompare_right intmatch_count int) next = make ([]int, length) next[0] = 0next[1] = 0for I: = 2; i < length; i++ {middle = I/2match_count = 0if i%2 = = 0 {for J: = 0; J < Middle; J + + {compare_left = 0compare_right = i-1-Jfo R Compare_left <= J {if sub[compare_left]! = Sub[compare_right] {break}compare_left++compare_right++}if compare_left = = j+1 {Match_count++}}next[i] = Match_count} else {for j: = 0; J <= Middle; j + + {compare_left = 0compare_right = I-1 -Jfor Compare_left <= J {if sub[compare_left]! = Sub[compare_right] {break}compare_left++compare_right++}if compare_ left = = j+1 {Match_count++}}next[i] = Match_count}}return next}func revisenextvaluearray (Next []int) []int {var length int = Len (next) for I: = 2; i < length; i++ {if next[i] = = Next[next[i]] {next[i] = Next[next[i]]}}return next}//looking for a sub substring between start-end in content/successfully returns the start subscript of the match success, the match fails to return -1func KMP (content []byte, Start_index int, End_index int, sub []byte) (index int) {var (next []int = Revisenextvaluearray (Getnextvaluearray (sub)) Sub_index int = 0sub_length int = len (sub)) for I: = Start_index; I <= End_index; i++ {if content[i] = = Sub[sub_index] {match_start: = IFOR J: = Sub_index; J <= Sub_length; j + + {if J = = Sub_length {ret Urn match_start-sub_index}if i >= end_index | | Content[i]! = sub[j] {sub_index = Next[j]break}i++}}}return-1}func main () {content: = []byte ("Why every programming Langu Age use the ' Hello World as the first Test??? ') Sub: = []byte ("Hello World") fmt. Println (KMP (content, 0, Len (content)-1, sub))}
If reproduced please specify the source: http://blog.csdn.net/gophers/article/details/23128345