Number of Segments in a String - Problem
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.
Note that the string may contain leading/trailing spaces or multiple spaces between segments.
Input & Output
Example 1 — Basic Case
$
Input:
s = "Hello, my name is John"
›
Output:
5
💡 Note:
The five segments are: "Hello,", "my", "name", "is", "John"
Example 2 — Multiple Spaces
$
Input:
s = "Hello"
›
Output:
1
💡 Note:
Only one segment: "Hello"
Example 3 — Leading/Trailing Spaces
$
Input:
s = " Hello world "
›
Output:
2
💡 Note:
Two segments: "Hello" and "world", ignoring leading/trailing spaces
Constraints
- 0 ≤ s.length ≤ 300
- s consists of lowercase and uppercase English letters, digits, or one of the following characters: ' ', '.', ',', '?', '!', '"', '/', '\', '(', ')'
Visualization
Tap to expand
Understanding the Visualization
1
Input
String with words separated by spaces
2
Process
Identify non-space character sequences
3
Output
Count of segments found
Key Takeaway
🎯 Key Insight: Count groups of non-space characters, ignoring multiple spaces between them
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code