28. Find the Index of the First Occurrence in a String
Example 1
Example 2
Constraints
Solution
func strStr(haystack string, needle string) int {
if len(haystack) < len(needle) {
return -1
}
for i := 0; i < len(haystack); i++ {
if haystack[i] == needle[0] {
if len(haystack)-i < len(needle) {
return -1
}
if haystack[i:i+len(needle)] == needle {
return i
}
}
}
return -1
}
Last updated