Skip to content

Commit 72e5045

Browse files
authored
Merge pull request #10 from fabiothiroki/strstr
[WIP] Implementing strstr
2 parents 007b4d0 + 7c17a54 commit 72e5045

File tree

3 files changed

+102
-0
lines changed

3 files changed

+102
-0
lines changed

string/strstr/README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Implement strStr()
2+
3+
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

string/strstr/strstr.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package strstr
2+
3+
// StrStr implements the respective method of C++
4+
func StrStr(haystack string, needle string) int {
5+
6+
if len(needle) == 0 {
7+
return 0
8+
}
9+
10+
if len(needle) > len(haystack) {
11+
return -1
12+
}
13+
14+
foundIndex := -1
15+
j := -1
16+
17+
for i := range haystack {
18+
19+
if foundIndex == -1 {
20+
if haystack[i] == needle[0] {
21+
if len(needle) == 1 {
22+
return i
23+
}
24+
25+
foundIndex = i
26+
j = 1
27+
continue
28+
} else if len(haystack)-i <= len(needle) {
29+
return -1
30+
} else {
31+
continue
32+
}
33+
}
34+
35+
if foundIndex != -1 {
36+
if haystack[i] == needle[j] {
37+
38+
if j == len(needle)-1 {
39+
return foundIndex
40+
}
41+
j++
42+
43+
} else {
44+
foundIndex = -1
45+
}
46+
}
47+
48+
}
49+
50+
return foundIndex
51+
}

string/strstr/strstr_test.go

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package strstr
2+
3+
import "testing"
4+
5+
func TestHello(t *testing.T) {
6+
7+
r := StrStr("hello", "ll")
8+
9+
if r != 2 {
10+
t.Errorf("Got: %d, want: %d.", r, 2)
11+
}
12+
}
13+
14+
func TestNotFound(t *testing.T) {
15+
16+
r := StrStr("aaaaa", "bba")
17+
18+
if r != -1 {
19+
t.Errorf("Got: %d, want: %d.", r, -1)
20+
}
21+
}
22+
23+
func TestReset(t *testing.T) {
24+
25+
r := StrStr("aaabaaaabb", "abb")
26+
27+
if r != 7 {
28+
t.Errorf("Got: %d, want: %d.", r, 7)
29+
}
30+
}
31+
32+
func TestShortNeedle(t *testing.T) {
33+
34+
r := StrStr("aaa", "a")
35+
36+
if r != 0 {
37+
t.Errorf("Got: %d, want: %d.", r, 0)
38+
}
39+
}
40+
41+
func TestBigNeedle(t *testing.T) {
42+
43+
r := StrStr("aaa", "aaaa")
44+
45+
if r != -1 {
46+
t.Errorf("Got: %d, want: %d.", r, -1)
47+
}
48+
}

0 commit comments

Comments
 (0)