Number of Segments in a String

Given a string `s`, return the number of segments in it. A segment is a maximal run of consecutive characters that are not spaces.

30:00

Number of Segments in a String
easy
Free written solution
Topics
Companies

Given a string s, return the number of segments in it. A segment is a maximal run of consecutive characters that are not spaces.

Example 1:
Input: {"s":"Hello, my name is John"}
Output: 5
Constraints:
  • 0≤s.length≤3000 \leq s.\text{length} \leq 300

  • s consists of lowercase and uppercase English letters, digits, or one of !@#$%^&*()_+-=',.:.

  • The only space character in s is ' '.

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"s":"Hello, my name is John"}

s: a flag marks each left edge, where a non-space follows a space

H
e
l
l
o
,
·
m
y
·
n
a
m
e
·
i
s
·
J
o
h
n

A segment begins exactly where a non-space character follows a space (or the start of the string). Count those left edges.

segments

count 0

Variables
VariableValue
segments0
DepthFunction Call
Stack empty
0/23