Skip to content

Instantly share code, notes, and snippets.

@thanhpp
Last active November 1, 2021 07:08
Show Gist options
  • Save thanhpp/db459bd078c941b130476bf7c85dbe3c to your computer and use it in GitHub Desktop.
Save thanhpp/db459bd078c941b130476bf7c85dbe3c to your computer and use it in GitHub Desktop.
Bayer - Moore string matching
package main
import (
"fmt"
)
func main() {
var (
s = 0
P = "acabac"
m = len(P)
T = "aabacbdcaacaacabac"
n = len(T)
)
for s <= n-m {
j := m
for j > 0 && T[j+s-1] == P[j-1] {
j = j - 1
}
if j == 0 {
fmt.Println("pos ", s)
s = s + 1
} else {
k := last(T[j+s-1], P)
s = s + max(j-k, 1)
}
}
}
func last(char byte, search string) int {
for j := len(search) - 1; j >= 0; j-- {
if search[j] == char {
return j + 1
}
}
return 0
}
func max(a, b int) int {
if a > b {
return a
}
return b
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment