Skip to content

Commit 1013f84

Browse files
committed
enhance code and stash KnuthMorrisPratt
1 parent 4ea7674 commit 1013f84

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

string/matching/string-matching.go

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,29 @@ func Naive(s, txt string) bool {
3030
if lentxt > lens {
3131
return false
3232
}
33-
for i := 0; i < lens-lentxt; i++ {
33+
for i := 0; i <= lens-lentxt; i++ {
34+
for j := 0; j <= lentxt; j++ {
35+
if j == lentxt {
36+
return true
37+
}
38+
if txt[j] != s[i+j] {
39+
break
40+
}
41+
}
42+
}
43+
return false
44+
}
45+
46+
/*
47+
Knuth-Morris-Pratt 字符串匹配算法(即 KMP 算法)
48+
http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html
49+
*/
50+
func KnuthMorrisPratt(s, txt string) bool {
51+
lens, lentxt := len(s), len(txt)
52+
if lentxt > lens {
53+
return false
54+
}
55+
for i := 0; i <= lens-lentxt; i++ {
3456
for j := 0; j <= lentxt; j++ {
3557
if j == lentxt {
3658
return true

string/matching/string-matching_test.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,19 @@ func Test_Naive(t *testing.T) {
88
result := []bool{true, false, false, true}
99
for i := 0; i < len(sList); i++ {
1010
if Naive(sList[i], txtList[i]) != result[i] {
11-
t.Log(sList[i], txtList[i], result[i])
11+
t.Log(sList[i], txtList[i], result[i], "result is:", Naive(sList[i], txtList[i]))
12+
t.Fail()
13+
}
14+
}
15+
}
16+
17+
func Test_KnuthMorrisPratt(t *testing.T) {
18+
sList := []string{"BBC ABCDAB ABCDABCDABDE", "", "ab", "abc"}
19+
txtList := []string{"ABCDABD", "a", "c", "c"}
20+
result := []bool{true, false, false, true}
21+
for i := 0; i < len(sList); i++ {
22+
if KnuthMorrisPratt(sList[i], txtList[i]) != result[i] {
23+
t.Log(sList[i], txtList[i], result[i], "result is:", KnuthMorrisPratt(sList[i], txtList[i]))
1224
t.Fail()
1325
}
1426
}

0 commit comments

Comments
 (0)