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 c979212

Browse files
author
Openset
committed
Add: length_of_last_word
1 parent 05f2a67 commit c979212

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,13 @@
11
package length_of_last_word
2+
3+
func lengthOfLastWord(s string) int {
4+
wc, l := 0, len(s)-1
5+
for i := l; i >= 0; i-- {
6+
if s[i] != ' ' {
7+
wc++
8+
} else if wc > 0 {
9+
return wc
10+
}
11+
}
12+
return wc
13+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1 +1,22 @@
11
package length_of_last_word
2+
3+
import "testing"
4+
5+
func TestLengthOfLastWord(t *testing.T) {
6+
tests := map[string]int{
7+
"Hello World": 5,
8+
"Hello": 5,
9+
"this is a string": 6,
10+
"": 0,
11+
" ": 0,
12+
"a ": 1,
13+
"b ": 1,
14+
}
15+
16+
for input, expected := range tests {
17+
output := lengthOfLastWord(input)
18+
if output != expected {
19+
t.Fatalf("input: %v, output: %v, expected: %v", input, output, expected)
20+
}
21+
}
22+
}

0 commit comments

Comments
(0)

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