Skip to content

Instantly share code, notes, and snippets.

@aita
Created October 14, 2020 03:20
Show Gist options
  • Save aita/22d000a528cc03ac46eca9dfe1e94bd2 to your computer and use it in GitHub Desktop.
Save aita/22d000a528cc03ac46eca9dfe1e94bd2 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
)
func prefixTable(p string) []int {
f := make([]int, len(p))
i, j := 1, 0
for i < len(p) {
if p[i] == p[j] {
f[i] = j + 1
i++
j++
} else if j > 0 {
j = f[j-1]
} else {
f[i] = 0
i++
}
}
return f
}
func KMP(s, p string) int {
i, j := 0, 0
f := prefixTable(p)
for i < len(s) {
if s[i] == p[j] {
if j == len(p)-1 {
return i - j
} else {
i++
j++
}
} else if j > 0 {
j = f[j-1]
} else {
i++
}
}
return -1
}
func main() {
f := prefixTable("ababaca")
p := KMP("bacbabababacaca", "ababaca")
fmt.Println(f, p)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment