simple one pass, count changes from "space" to "none-space"

  • 0

    The number of changes from space to non-space is the number of segments.

    class Solution(object):
        def countSegments(self, s):
            :type s: str
            :rtype: int
            wasSpace, count = True, 0
            for c in s:
                isSpace = c == ' '
                if wasSpace and not isSpace:
                    count += 1
                wasSpace = isSpace
            return count

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.