434 Number of Segments in a String

Count the number of segments in a string, where a segment is defined to be a contiguous sequence of non-space characters.

Please note that the string does not contain anynon-printablecharacters.

Example:

Input:
 "Hello, my name is John"

Output:
 5

Time Complexity: O(n) time and space

Not a great problem, in my opinion

class Solution:
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        split_str = s.split()
        return len(split_str)


obj = Solution()
assert(obj.countSegments("kasjd asdj, adkja askjd") == 4)
assert(obj.countSegments("      ") == 0)
assert(obj.countSegments("") == 0)

Last updated