计算字符串中单词的数量,单词是一个连续无空格符的字符序列 字符串不包含任何非打印字符
Example:
Input: “Hello, my name is John” Output: 5
1、注意题意要求为“连续无空格符的字符序列”,意思就是只要字符序列无空格符都可以算是单词
def countSegments(self
, s
):
"""
:type s: str
:rtype: int
"""
word
= False
count
= 0
for i
in s
:
if i
!= " ":
word
= True
else:
if word
== True:
count
+= 1
word
= False
if word
== True:
count
+= 1
return count
2、利用len(s.split(" "))方法(参考他人)
def countSegments(self
, s
):
"""
:type s: str
:rtype: int
"""
return len(s
.split
(" "))
算法题来自:https://leetcode-cn.com/problems/number-of-segments-in-a-string/description/