Another version of classic KMP algorithm
iWeslie opened this issue · 0 comments
iWeslie commented
Brief Intro
I think the original article for KMP is not clear enough for understanding the theory and idea of KMP and there may be another version of KMP. Here is the code.
func getNext(pattern: [Character]) -> [Int] {
var i = 0
var j = -1
var next = Array(repeating: 0, count: pattern.count)
next[0] = -1
while i < pattern.count - 1 {
if j == -1 || pattern[i] == pattern[j] {
i += 1
j += 1
next[i] = j
} else {
j = next[j]
}
}
return next
}
func kmp(text: [Character], pattern: [Character]) -> Int {
let next = getNext(pattern: pattern)
var i = 0
var j = 0
while i < text.count && j < pattern.count {
if j == -1 || text[i] == pattern[j] {
i += 1
j += 1
} else {
j = next[j]
}
}
if j == pattern.count {
return i - j
}
return -1
}
let textString = "BBC ABCDAB ABCDABCDABDE"
let patternString = "ABCDABD"
let text = Array(textString)
let pattern = Array(patternString)
kmp(text: text, pattern: pattern)
More Details
First, we try Brute-Force. Then optimize it by a next array to skip searching index.
So, will this version of KMP is more clear?