实现 Sunday 匹配 needle在最末尾的时候返回结果异常
mfacious opened this issue · comments
s := "hello world abc is a test chars in program develop comm"
index := strStrSunday(s, "common")
fmt.Println("common index is", index)
正常应该返回-1, 实际会返回54 什么的
附上根据原链接java 版本实现的一个方法:
`
func strStrSunday(haystack string, needle string) int {
if len(haystack) < len(needle) {
return -1
}
if haystack == needle {
return 0
}
originIndex := 0
aimIndex := 0
nextIndex := 0
for aimIndex < len(needle) {
if originIndex > len(haystack)-1 {
return -1
}
if haystack[originIndex] == needle[aimIndex] {
originIndex++
aimIndex++
} else {
nextIndex = originIndex - aimIndex + len(needle)
if nextIndex < len(haystack) {
offset := strings.LastIndex(needle, string(haystack[nextIndex]))
if offset == -1 {
originIndex = nextIndex + 1
} else {
originIndex = nextIndex - offset
}
aimIndex = 0
} else {
return -1
}
}
}
return originIndex - aimIndex
}
`