package main
import "fmt"
func main() {
subStr := "abab"
mainStr := "bababdrt"
//for i,k :=range GetNext(subStr){
// fmt.Printf("i:%d,j:%d\n",i,k)
//}
pos ,_:= KMPSearch(mainStr,subStr)
fmt.Println(pos)
}
//kmp算法,实现子串查询
func KMPSearch(mainStr,subStr string)(pos int,err error){
mLen := len(mainStr)
sLen := len(subStr)
nextArray := GetNext(subStr)
j := 0
drop_place:
for i:=0; i<mLen-sLen ;{
for ;j< sLen;{
if mainStr[i] == subStr[j]{
//fmt.Printf("i:%d,j:%d\n",i,j)
if j== sLen-1{
pos = i-sLen+1
break drop_place
}
j++
i++
}else{
k := nextArray[j]
if k ==-1{
j = 0
i++
}else{
j= k
}
break
}
}
}
return pos,nil
}
//获取next数组,next数组为对应位置所要跳转位置
func GetNext(str string)[]int {
strLen := len(str)
nextArray := make([]int,len(str))
if strLen > 0{
nextArray[0] = -1
j := 0
k := -1
for ;j<strLen-1;{
if k ==-1 || str[j] == str[k]{
j+=1
k+=1
nextArray[j] = k
}else {
k = nextArray[k]
}
}
}
return nextArray
}
KMP算法golang实现
最新推荐文章于 2023-05-12 21:02:36 发布