1、问题描述
统计字符串中的单词个数,其中一个单词定义为不含空格的连续字符串。
2、问题示例
输入"Hello, my name is John.",输出5。
3、代码实现
class Solution:
def countSegments(self, s):
res = 0
for i in range(len(s)):
if s[i] != ' ' and (i == 0 or s[i-1] == ' '):
res += 1
return res
if __name__ == '__main__':
solution = Solution()
n = "Hello, my name is John."
msg = solution.countSegments(n)
print(msg)