此算法实现的核心就是每次向后移动一位进行匹配,关键部分next数组,GetNext函数是失效函数,next数据就是匹配串字符串最长匹配前缀和最长匹配后缀的关系。
代码片段如下:
package main
func StringSearch(str, searchStr string) int {
next := GetNext(searchStr)
j := 0
for i := 0; i < len(str); i++ {
for j != 0 && str[i] != searchStr[j] {
j = next[j-1] + 1
}
if str[i] == searchStr[j] {
j++
}
if j == len(searchStr) {
return i - j + 1
}
}
return -1
}
func GetNext(needle string) []int {
next := make([]int, len(needle))
next[0] = -1
k := -1
for i := 1; i < len(needle); i++ {
for k != -1 && needle[k+1] != needle[i] {
k = next[k]
}
if needle[k+1] == needle[i] {
k++
}
next[i] = k
}
return next
}