-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: adding testing for kmp algorithm
- Loading branch information
Showing
2 changed files
with
121 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
package algorithm | ||
|
||
|
||
const ( | ||
PatternSize int = 100 | ||
) | ||
|
||
func SerchNext(stack string, needle string) int { | ||
ret := KMP(stack, needle) | ||
if len(ret) > 0 { | ||
return ret[len(ret)-1] | ||
} | ||
|
||
return -1 | ||
} | ||
|
||
func SearchString(stack string, needle string) int { | ||
|
||
ret := KMP(stack, needle) | ||
if len(ret) > 0 { | ||
return ret[0] | ||
} | ||
|
||
return -1 | ||
} | ||
|
||
func KMP(stack string, needle string) []int { | ||
next := preKMP(needle) | ||
i := 0 | ||
j := 0 | ||
m := len(needle) | ||
n := len(stack) | ||
|
||
x := []byte(needle) | ||
y := []byte(stack) | ||
var ret []int | ||
|
||
if m == 0 || n == 0 { | ||
return ret | ||
} | ||
|
||
if n < m { | ||
return ret | ||
} | ||
|
||
for j < n { | ||
for i > -1 && x[i] != y[j] { | ||
i = next[i] | ||
} | ||
i++ | ||
j++ | ||
|
||
if i >= m { | ||
ret = append(ret, j-i) | ||
i = next[i] | ||
} | ||
} | ||
|
||
return ret | ||
} | ||
func preMP(x string) [PatternSize]int { | ||
var i, j int | ||
lenght := len(x) - 1 | ||
|
||
var mpNext [PatternSize]int | ||
i = 0 | ||
j = -1 | ||
mpNext[0] = -1 | ||
|
||
for i < lenght { | ||
for j > -1 && x[i] != x[j] { | ||
j = mpNext[j] | ||
} | ||
i++ | ||
j++ | ||
mpNext[i] = j | ||
} | ||
|
||
return mpNext | ||
} | ||
|
||
func preKMP(x string) [PatternSize]int { | ||
var i, j int | ||
lenght := len(x) - 1 | ||
|
||
var kmpNext [PatternSize]int | ||
i = 0 | ||
j = -1 | ||
kmpNext[0] = -1 | ||
|
||
for i < lenght { | ||
for j > -1 && x[i] != x[j] { | ||
j = kmpNext[j] | ||
} | ||
i++ | ||
j++ | ||
|
||
if x[i] == x[j] { | ||
kmpNext[i] = kmpNext[j] | ||
} else { | ||
kmpNext[i] = j | ||
} | ||
} | ||
return kmpNext | ||
} |