-
前缀:aabaaf :a,aa,aab,aaba,aabaa
-
后缀:f,af,aaf,baaf,abaaf
-
最长相等前后缀:a-0 aa-1 aab-0 aaba-1 aabaa-2 aabaaf-0
-
0 1 0 1 2 0就是aabaaf前缀表-next数组
//首先获取next i指向后缀末尾位置,j指向前缀末尾位置,遇到冲突看前一位
func getNext(s string,next []int){
j :=0
next[0] = j
for i:=1;i<len(s);i++{
for j>0&&s[i]!=s[j]{
j = next[j-1]
}
if s[i]==s[j]{
j++
}
next[i] = j
}
}
func strStr(haystack string, needle string) int {
n := len(needle)
if n == 0 {
return 0
}
j := 0
next := make([]int, n)
getNext(next, needle)
for i := 0; i < len(haystack); i++ {
for j > 0 && haystack[i] != needle[j] {
j = next[j-1] // 回退到j的前一位
}
if haystack[i] == needle[j] {
j++
}
if j == n {
return i - n + 1
}
}
return -1
}