Sunday, February 24, 2019

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

class Solution(object):
    def countSegments1(self, s):
        """
        :type s: str
        :rtype: int
        """
        return len(s.split())
   
    def countSegments(self, s):
        temp = ''
        count = 0
        for i in s:
            if i != ' ':
                temp += i
            else:
                if temp: count += 1
                temp = ''
        if temp: count += 1
        return count

No comments:

Post a Comment