Number of Segments in a String

easy string

Problem

Given a string s, return the number of segments — maximal runs of non-space characters.

Inputs = "Hello, my name is John"
Output5
Each segment starts where a non-space follows a space or the start of the string.

def 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;
}
Time: O(n) Space: O(1)