题目描述
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
解题代码
func strStr(haystack string, needle string) int { if len(haystack) < len(needle) { return -1 } if len(needle) == 0 || haystack == needle{ return 0 } index := 0 for len(haystack) >= index + len(needle) { if haystack[index:index + len(needle)] == needle { return index } index++ } return -1 }
提交结果