Skip to content

Commit 4e463dc

Browse files
committed
Add length-of-last-word
1 parent 06fcdb0 commit 4e463dc

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Diff for: length-of-last-word.go

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
)
6+
7+
func main() {
8+
fmt.Println(lengthOfLastWord("a"))
9+
fmt.Println(lengthOfLastWord("abc "))
10+
fmt.Println(lengthOfLastWord(" abc"))
11+
}
12+
13+
func lengthOfLastWord(s string) int {
14+
length := len(s)
15+
spacePos := -1
16+
nonSpacePos := -1
17+
for i := length - 1; i >= 0; i-- {
18+
if s[i] != ' ' {
19+
if nonSpacePos < 0 {
20+
nonSpacePos = i
21+
}
22+
} else if nonSpacePos >= 0 {
23+
spacePos = i
24+
break
25+
}
26+
}
27+
return nonSpacePos - spacePos
28+
}

0 commit comments

Comments
 (0)