基本思路,当遇到空格任何不是字符的值都直接count+=1,有边界情况,当下标为0,或者前一个下标为空格的时候,都要纳入考虑,代码如下:
class Solution:
def countSegments(self, s: str) -> int:
count=0
for i in range (len(s)):
if (i==0 or s[i-1]==" ")and s[i]!=" ":
count+=1
return count