-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolution58.go
More file actions
52 lines (47 loc) · 1.04 KB
/
solution58.go
File metadata and controls
52 lines (47 loc) · 1.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package solution58
import (
"strings"
)
// ============================================================================
// 58. Length Of Last Word
// URL: https://leetcode.com/problems/length-of-last-word/
// ============================================================================
/*
goos: linux
goarch: amd64
pkg: GoLeetCode/solutions/58---Length-Of-Last-Word
cpu: 13th Gen Intel(R) Core(TM) i7-13700K
Benchmark_lengthOfLongestSubstring
Benchmark_lengthOfLongestSubstring-24 269786204 4.452 ns/op 0 B/op 0 allocs/op
PASS
*/
func lengthOfLastWord(s string) int {
length := len(s)
if length < 1 || length > 10_000 {
return 0
}
c := 0
word := false
for i := length - 1; i >= 0; i-- {
if s[i] == 32 && !word {
word = false
c = 0
continue
}
if s[i] == 32 && word {
return c
}
word = true
c++
}
return c
}
func lengthOfLastWord_stringsField(s string) int {
length := len(s)
if length < 1 || length > 10_000 {
return 0
}
sl := strings.Fields(s)
word := sl[len(sl)-1]
return len(word)
}