434.Number of Segments in a String

Tags: [buffer], [string]

Link: https://leetcode.com/problems/number-of-segments-in-a-string/?tab=Description

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 any non-printable characters.

Example:

Input:
 "Hello, my name is John"

Output:
 5

Solution: buffer

class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0

        buff = []
        counter = 0
        for c in s:
            if c == ' ':
                if buff:
                    counter += 1
                    buff = []
            else:
                buff.append(c)

        if buff:
            counter += 1

        return counter

Note:

  • Time complexity = O(n), n is the number of the characters in the given string.

results matching ""

    No results matching ""