Created
June 12, 2020 18:57
-
-
Save polynomialspace/1cae43e89ae87a73ba9893c030851d93 to your computer and use it in GitHub Desktop.
Boyer moore impl in go re: https://leetcode.com/problems/implement-strstr
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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