28. 找出字符串中第一个匹配项的下标
func strStr(haystack string, needle string) int {
//KMP算法
j := 0
next := make([]int , len(needle))
getNext(next,needle)
for i := 0 ; i < len(haystack) ; i++{
for haystack[i] != needle[j] && j > 0{
j = next[j - 1]
}
if(haystack[i] == needle[j]){
j++
}
if(j == len(needle)){
return i - j + 1
}
}
return -1
}
func getNext(next []int, s string){
j := 0
next[0] = j
for i := 1 ; i < len(s) ; i++{
for s[i] != s[j] && j > 0{
j = next[j - 1]
}
if(s[i] == s[j]){
j++
}
next[i] = j
}
}
459. 重复的子字符串
func repeatedSubstringPattern(s string) bool {
j := 0
next := make([]int , len(s))
for i := 1 ; i < len(s) ; i++{
for s[j] != s[i] && j > 0{
j = next[j - 1]
}
if(s[j] == s[i]){
j++
}
next[i] = j
}
a := len(s)
if(next[len(s)-1] > 0 && a % (a - next[a-1]) == 0){
return true
}
return false
}
总结
KMP算法能够手写…但不知道为什么要这么用… 感觉像直接背了套模板硬写