https://leetcode.cn/problems/find-the-index-of-the-first-occurrence-in-a-string/description/?envType=study-plan-v2&envId=top-interview-150
package leetcode150 import "testing" func TestStrStr(t *testing.T) { haystack := "sadbutsad" needle := "sad" res := strStr(haystack, needle) println(res) } func strStr(haystack string, needle string) int { next := make([]int, len(needle)) next[0] = 0 i, j := 1, 0 for ; i < len(needle); i++ { for j > 0 && needle[i] != needle[j] { j = next[j-1] } if needle[i] == needle[j] { j++ } next[i] = j } //for _, o := range next { // print(o) // print(" ") //} //println() for i, j = 0, 0; i < len(haystack); i++ { for j > 0 && haystack[i] != needle[j] { j = next[j-1] } if haystack[i] == needle[j] { j++ } if j == len(needle) { return i - j + 1 } } return -1 }
浙公网安备 33010602011771号