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.

Example:

1
2
Input: "Hello, my name is John"
Output: 5

思路

统计字符串的片段数。片段之间用空格隔开。

注意一开始如果有空格的话,需要去掉一个间隔数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class (object):
def countSegments(self, s):
"""
:type s: str
:rtype: int
"""
length = len(s)
count = 0
if (length == 0):
return 0
else:
for i in range(length-1):
if (s[i] == ' ' and s[i+1] != ' '):
count += 1
if (s[0] == ' '):
return count
else:
return count+1