Skip to content

Commit 2e91167

Browse files
author
Shuo
committed
A: Check If a Word Occurs As a Prefix of Any Word in a Sentence
1 parent 11d26c3 commit 2e91167

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
package problem1455
2+
3+
import "strings"
4+
5+
func isPrefixOfWord(sentence string, searchWord string) int {
6+
items := strings.Fields(sentence)
7+
for i, item := range items {
8+
if strings.HasPrefix(item, searchWord) {
9+
return i + 1
10+
}
11+
}
12+
return -1
13+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package problem1455
2+
3+
import "testing"
4+
5+
type testType struct {
6+
sentence string
7+
searchWord string
8+
want int
9+
}
10+
11+
func TestIsPrefixOfWord(t *testing.T) {
12+
tests := [...]testType{
13+
{
14+
sentence: "i love eating burger",
15+
searchWord: "burg",
16+
want: 4,
17+
},
18+
{
19+
sentence: "this problem is an easy problem",
20+
searchWord: "pro",
21+
want: 2,
22+
},
23+
{
24+
sentence: "i am tired",
25+
searchWord: "you",
26+
want: -1,
27+
},
28+
{
29+
sentence: "i use triple pillow",
30+
searchWord: "pill",
31+
want: 4,
32+
},
33+
{
34+
sentence: "hello from the other side",
35+
searchWord: "they",
36+
want: -1,
37+
},
38+
}
39+
for _, tt := range tests {
40+
got := isPrefixOfWord(tt.sentence, tt.searchWord)
41+
if got != tt.want {
42+
t.Fatalf("in: %v, got: %v, want: %v", tt.sentence, got, tt.want)
43+
}
44+
}
45+
}

0 commit comments

Comments
 (0)