这道题直接使用语言内置的 split 函数可直接分离出字符串中的每个单词,但是要注意区分两种情况:1、空串;2、多个空格连续,分割后会出现空字符的情况,应该舍弃
class Solution(object):def countSegments(self, s):""":type s: str:rtype: int"""if s == '':return 0ss = s.split(" ")count = 0for i in range(len(ss)):if len(ss[i]) != 0:count += 1return count
题解有另外一种解法
class Solution:def countSegments(self, s):segment_count = 0for i in range(len(s)):if (i == 0 or s[i - 1] == ' ') and s[i] != ' ':segment_count += 1return segment_count