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

题目大意:

计算字符串中的非空子串的个数。

解题思路:

用内置函数split即可

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

第二种方法:遍历array,如果s[i]不等于空格,s[i]前边一项为空格或者s[i]为首项,则count加一

class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        count = 0
        for i in xrange(len(s)):
            if s[i] !=' ' and (s[i-1] == ' ' or i == 0):
                count += 1
        return count

简化

class Solution(object):
    def countSegments(self, s):
        """
        :type s: str
        :rtype: int
        """
        return sum([s[i] != ' ' and (i == 0 or s[i - 1] == ' ') for i in range(len(s))])

Last updated

Was this helpful?