1 package main 2 3 import ( 4 "fmt" 5 ) 6 7 8 func getNext(str string) []int { 9 length := len(str) 10 next := make([]int, length) 11 next[0] = -1 12 for i := 1; i < length; i++ { 13 j := i - 1 14 for j > 0 { 15 if str[i-1] == str[next[j]] { 16 next[i] = next[j] + 1 17 break 18 } else { 19 j = next[j] 20 } 21 } 22 if j <= 0 { 23 next[i] = 0 24 } 25 } 26 for k := 0; k < length; k++ { 27 fmt.Print(next[k], " ") 28 } 29 return next 30 } 31 32 func kmp(parstr, substr string) int { 33 next := getNext(substr) 34 lengthp := len(parstr) 35 lengths := len(substr) 36 i, j := 0, 0 37 for i < lengthp && j < lengths { 38 if parstr[i] == substr[j] { 39 i++ 40 j++ 41 } else if next[j] == -1 { 42 i++ 43 j = 0 44 } else { 45 j = next[j] 46 } 47 } 48 if j < lengths { 49 return -1 50 } else { 51 return i - lengths 52 } 53 } 54 55 func main() { 56 fmt.Println(kmp("abaababaafdsbfabcaab", "aababcaab")) 57 }