Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

实现 Sunday 匹配 needle在最末尾的时候返回结果异常 #65

Open
mfacious opened this issue Sep 6, 2022 · 0 comments
Open

Comments

@mfacious
Copy link

mfacious commented Sep 6, 2022

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

}
`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant