434. 字符串中的单词数
统计字符串中的单词个数,这里的单词指的是连续的不是空格的字符。 请注意,你可以假定字符串里不包括任何不可打印的字符。 示例: 输入: "Hello, my name is John" 输出: 5 思路详见注释。 1 class Solution(object): 2 def countSegments(self, s): 3 """ 4 :type s: str 5 :rtype: int 6 """ 7 if len(s.split()) == 0: 8 return 0 9 # 设置计数器,初始值为1 10 index = 0 11 # 遍历字符串,如果当前遇到的字符是字母前一个字符是空格时,计数器增1 12 # 当然,字符串第一个字符单独考虑 13 for i in range(len(s)): 14 if (i == 0 or s[i - 1] == ' ' ) and s[i].isalnum(): 15 index += 1 16 return index 17 18 def countSegments2(self, s): 19 """ 20 :type s: str 21 :rtype: int 22 """ 23 # 设置计数器,初始值为1 24 index = 1 25 # 遍历字符串,如果当前遇到的字符不是字母,那么在遇到下一个字母时,计数器增1 26 for