Kmp Function kmp performing the Knuth-Morris-Pratt algorithm.
(word, text string, patternTable []int)
| 2 | |
| 3 | // Kmp Function kmp performing the Knuth-Morris-Pratt algorithm. |
| 4 | func Kmp(word, text string, patternTable []int) []int { |
| 5 | if len(word) > len(text) { |
| 6 | return nil |
| 7 | } |
| 8 | |
| 9 | var ( |
| 10 | i, j int |
| 11 | matches []int |
| 12 | ) |
| 13 | for i+j < len(text) { |
| 14 | |
| 15 | if word[j] == text[i+j] { |
| 16 | j++ |
| 17 | if j == len(word) { |
| 18 | matches = append(matches, i) |
| 19 | |
| 20 | i = i + j |
| 21 | j = 0 |
| 22 | } |
| 23 | } else { |
| 24 | i = i + j - patternTable[j] |
| 25 | if patternTable[j] > -1 { |
| 26 | j = patternTable[j] |
| 27 | } else { |
| 28 | j = 0 |
| 29 | } |
| 30 | } |
| 31 | } |
| 32 | return matches |
| 33 | } |
| 34 | |
| 35 | // table building for kmp algorithm. |
| 36 | func table(w string) []int { |