[leetcode: Python]434. Number of Segments in a String

Title:
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

方法一:52ms

class Solution(object):
    def countSegments(self, s):
        """ :type s: str :rtype: int """
        if s.isspace():
            return  0
        s1 = s.strip()
        if len(s1) == 0:
            return  0
        d =[0]
        m = list(s1)
        while m:
            if m[0] != ' ':
                d[-1] += 1
            else:
                d.append(0)
            m.pop(0)
        return len(d) - d.count(0)

方法二:32ms

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

…业务不熟练啊

你可能感兴趣的:(LeetCode,python)