File tree Expand file tree Collapse file tree 3 files changed +102
-0
lines changed Expand file tree Collapse file tree 3 files changed +102
-0
lines changed Original file line number Diff line number Diff line change
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.
Original file line number Diff line number Diff line change
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
+ }
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments