2025-07-29 15:52:23 +0000 UTC

Number of Segments in a String

Code

class Solution:
    def countSegments(self, s: str) -> int:
        length = len(s)
        count = 0
        is_segment = False
        for char in s:
            is_space = char == " "
            if not is_segment and not is_space:
                is_segment = True
                count += 1
            elif is_space:
                is_segment = False
        return count