def__next_arr(self, s): n = len(s) dp = [0] * n for i inrange(1, n): index = i while index > 0and s[dp[index - 1]] != s[i]: index = dp[index - 1] if s[dp[index - 1]] == s[i]: dp[i] = dp[index - 1] + 1 else: dp[i] = 0 return dp
funcmain() { var s string s = "CEBDAEEAACEBDAE"//匹配串 target := "EBDAE"// 模式串 ans := kmp(s, target) fmt.Println(ans) } funccalNext(s string) []int { n := len(s) var index int dp := make([]int, n) for i := 1; i < n; i++ { index = i for index > 0 && s[dp[index-1]] != s[i] { index = dp[index-1] } if index == 0 { if s[0] == s[i] { dp[i] = 1 } else { dp[i] = 0 } } else { dp[i] = dp[index-1] + 1 }
} return dp } funckmp(s, target string) []int { var index int n_s, n_t := len(s), len(target) next_arr := calNext(target) var ans []int for i := 0; i < n_s; i++ { if s[i] == target[index] { index++ } else { for index > 0 && s[i] != target[next_arr[index-1]] { index = next_arr[index-1] } } if n_t == index { ans = append(ans, i-n_t+1) index = next_arr[index-1] } } return ans }