180. Number of Segments in a String

EasyStringString

Given a string s, return the number of segments in the string.

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

Multiple consecutive spaces count as one separator.

Input: A single string s (may contain leading/trailing/multiple spaces).

Output: An integer — the number of segments.

Examples

Example 1
Input: Hello, my name is John
Output: 5
Explanation: 5 non-space segments: 'Hello,','my','name','is','John'.
Example 2
Input:   foo bar  baz   
Output: 3
Explanation: Leading/trailing spaces ignored; 3 segments: 'foo','bar','baz'.
Example 3
Input:       
Output: 0
Explanation: Only spaces — no segments.

Constraints

Asked by

AmazonGoogleMicrosoft
Solve this problem in the editor →