Skip to content

Instantly share code, notes, and snippets.

@polynomialspace
Created June 12, 2020 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save polynomialspace/1cae43e89ae87a73ba9893c030851d93 to your computer and use it in GitHub Desktop.
Save polynomialspace/1cae43e89ae87a73ba9893c030851d93 to your computer and use it in GitHub Desktop.
func strStr(haystack string, needle string) int {
foundpos := -1
if len(needle) < 1 {
return 0
}
if len(needle) > len(haystack) {
return foundpos
}
/* Find unique char nearest the end of 'needle' to skip with */
skipmap, skip := make(map[rune]int), rune(needle[0])
for i, v := range needle {
if _, ok := skipmap[v]; !ok {
skipmap[v] = i
skip = v
}
}
for i := skipmap[skip]; i < len(haystack); i++ {
if s, ok := skipmap[rune(haystack[i])]; !ok {
i += s
} else if end := (i-s)+len(needle); end <= len(haystack) && needle == haystack[i-s:end] {
return i-s
}
}
return foundpos
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment