Skip to content

Instantly share code, notes, and snippets.

@hooluupog
Created August 4, 2013 07:38
Show Gist options
  • Save hooluupog/6149596 to your computer and use it in GitHub Desktop.
Save hooluupog/6149596 to your computer and use it in GitHub Desktop.
package main
import "fmt"
func Kmp(sstring string, pstring string, next []int) int {
i, j := 0, 0
for i < len(sstring) && j < len(pstring) {
if j == -1 || sstring[i] == pstring[j] {
i++
j++
} else {
j = next[j]
}
}
return i - len(pstring)
}
func Get_next(pstring string) []int {
next := make([]int, len(pstring))
next[0] = -1
for i, j := 0, -1; i < len(pstring)-1; {
if j == -1 || pstring[i] == pstring[j] {
i++
j++
next[i] = j
} else {
j = next[j]
}
}
return next
}
func main() {
sstring := "acabaabaabcacaabc"
pstring := "abaabcac"
next := make([]int, len(pstring))
next = Get_next(pstring)
fmt.Printf("The matching postion is : %d\n", Kmp(sstring, pstring, next))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment