Number of Segments in a String
LeetCode 434 · View on LeetCode
Count the number of segments (contiguous non-space characters) in a string.
Solution 1: strings.Fields (one-liner)
package main
import (
"fmt"
"strings"
)
func countSegments(s string) int {
return len(strings.Fields(s))
}
func main() {
fmt.Println(countSegments("Hello World Go")) // 3
}strings.Fields splits by any whitespace and ignores consecutive spaces — no empty strings.
Solution 2: Split and filter
func countSegments(s string) int {
sArr := strings.Split(s, " ")
seg := 0
for _, w := range sArr {
if strings.Trim(w, " ") != "" {
seg++
}
}
return seg
}strings.Split produces empty strings for consecutive spaces, so we filter them out. Allocates a slice.
Solution 3: Single pass — count word starts
func countSegments(s string) int {
segment := 0
for i, ch := range s {
if ch != ' ' && (i == 0 || s[i-1] == ' ') {
segment++
}
}
return segment
}Detects the start of each word: a non-space character where the previous character was a space (or it's the first character). O(n) time, O(1) space, no allocations.