Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 57dec75

Browse files
author
Openset
committed
Add: implement_strstr
1 parent 3525d60 commit 57dec75

File tree

3 files changed

+60
-0
lines changed

3 files changed

+60
-0
lines changed

‎solution/implement-strstr/README.md

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
## 28. Implement strStr()
2+
3+
Implement `strStr()`.
4+
5+
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
6+
7+
**Example 1:**
8+
```text
9+
Input: haystack = "hello", needle = "ll"
10+
Output: 2
11+
```
12+
13+
**Example 2:**
14+
```text
15+
Input: haystack = "aaaaa", needle = "bba"
16+
Output: -1
17+
```
18+
19+
**Clarification:**
20+
21+
What should we return when `needle` is an empty string? This is a great question to ask during an interview.
22+
23+
For the purpose of this problem, we will return 0 when `needle` is an empty string. This is consistent to C's `strstr()` and Java's `indexOf()`.
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
package implement_strstr
2+
3+
import "strings"
4+
5+
func strStr(haystack string, needle string) int {
6+
return strings.Index(haystack, needle)
7+
}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package implement_strstr
2+
3+
import "testing"
4+
5+
type caseType struct {
6+
haystack string
7+
needle string
8+
expected int
9+
}
10+
11+
func TestTwoSum(t *testing.T) {
12+
tests := [...]caseType{
13+
{
14+
haystack: "hello",
15+
needle: "ll",
16+
expected: 2,
17+
}, {
18+
haystack: "this is test string",
19+
needle: "a",
20+
expected: -1,
21+
},
22+
}
23+
24+
for _, tc := range tests {
25+
output := strStr(tc.haystack, tc.needle)
26+
if output != tc.expected {
27+
t.Fatalf("input: %v %v, output: %v, expected: %v", tc.haystack, tc.needle, output, tc.expected)
28+
}
29+
}
30+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /