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.
Algorithm
Counts the number of words (non-empty segments) in a string by traversing it and skipping spaces.
Code
class Solution:def countSegments(self, s: str) -> int:cnts, index = 0, 0sLen = len(s)while index < sLen: while index < sLen and s[index] == ' ':index += 1if index < sLen and s[index] != ' ':cnts += 1while index < sLen and s[index] != ' ':index += 1return cnts