Number of Segments in a String
Problem
Given a string s, return the number of segments — maximal runs of non-space characters.
s = "Hello, my name is John"5def count_segments(s):
count = 0
for i, ch in enumerate(s):
if ch != ' ' and (i == 0 or s[i-1] == ' '):
count += 1
return count
function countSegments(s) {
let count = 0;
for (let i = 0; i < s.length; i++) {
if (s[i] !== ' ' && (i === 0 || s[i - 1] === ' ')) count++;
}
return count;
}
class Solution {
public int countSegments(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) != ' ' && (i == 0 || s.charAt(i - 1) == ' ')) count++;
}
return count;
}
}
int countSegments(string s) {
int count = 0;
for (int i = 0; i < (int)s.size(); i++) {
if (s[i] != ' ' && (i == 0 || s[i - 1] == ' ')) count++;
}
return count;
}
Explanation
A "segment" is just a word — a run of non-space characters. Instead of splitting the string into a list, we count segments by spotting where each one begins. A segment starts exactly when a non-space character has a space (or the string start) right before it.
The code scans every character with its index i. The test is ch != ' ' and (i == 0 or s[i-1] == ' '): the current character must not be a space, and the previous slot must be either the start of the string or a space. Each time this is true we found a new segment, so count += 1.
This neatly handles extra spaces between words and never double-counts, because only the first character of each word satisfies the condition — later characters of the same word have a non-space neighbor before them.
Example: "Hello, my name is John". The characters starting a segment are H, m, n, i, and J — five starts, so the answer is 5.