We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 06fcdb0 commit 4e463dcCopy full SHA for 4e463dc
length-of-last-word.go
@@ -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