我试图实现knuth morris pratt算法。文本中出现的图案外观不会得到打印。count变量保存模式在字符串中出现了多少次的值。请帮助解决问题
package main
import "fmt"
func kmppre(pattern string, shiftarr []int) {
m := len(pattern)
i := 0
j := -1
for i < m {
for j >= 0 && pattern[i] != pattern[j] {
j = shiftarr[j]
}
i++
j++
shiftarr[i] = j
}
}
func kmp(text string, pattern string) int {
n := len(text)
m := len(pattern)
count := 0
i, j := 0, 0
shiftarr := make([]int, m+1)
kmppre(pattern, shiftarr)
for i < n {
for j >= 0 && text[i] != pattern[j] {
j = shiftarr[j]
}
i++
j++
if j == m {
count++
j = shiftarr[j]
}
}
return count
}
func main() {
fmt.Print("enter the text \n")
var text string
fmt.Scan(&text)
fmt.Print("enter the pattern string\n")
var pattern string
fmt.Scan(&pattern)
a := kmp(text, pattern)
fmt.Println(a)
}
凤凰求蛊
相关分类