0434. Number of Segments in a String

434. Number of Segments in a String #

Problem #

You are given a string s, return the number of segments in the string.

A segment is defined to be a contiguous sequence of non-space characters.

Example 1:

Input: s = "Hello, my name is John"
Output: 5
Explanation: The five segments are ["Hello,", "my", "name", "is", "John"]

Example 2:

Input: s = "Hello"
Output: 1

Example 3:

Input: s = "love live! mu'sic forever"
Output: 4

Example 4:

Input: s = ""
Output: 0

Constraints

  • 0 <= s.length <= 300
  • s consists of lower-case and upper-case English letters, digits or one of the following characters “!@#$%^&*()_+-=’,.:”.
  • The only space character in s is ' ‘.

Problem Summary #

Count the number of words in a string, where a word refers to a contiguous sequence of non-space characters.

Please note that you can assume the string does not include any non-printable characters.

Solution Approach #

  • Split by spaces to calculate the number of elements

Code #


package leetcode

func countSegments(s string) int {
	segments := false
	cnt := 0
	for _, v := range s {
		if v == ' ' && segments {
			segments = false
			cnt += 1
		} else if v != ' ' {
			segments = true
		}
	}
	if segments {
		cnt++
	}
	return cnt
}


Calendar Jun 25, 2026
Edit Edit this page
Total visits:   You are visitor No.
中文