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 i in range(len(s)): 27 if not s[i - 1].isalnum() and s[i].isalnum(): 28 index += 1 29 return index 30 31 def countSegments3(self, s): 32 """ 33 :type s: str 34 :rtype: int 35 """ 36 # 测试用例每个单词后都会有一个空格 37 return len(s.split()) 38 39 40 if __name__ == '__main__': 41 solution = Solution() 42 print(solution.countSegments(", , , , a, eaefa")) 43 print(solution.countSegments("Of all the gin joints in all the towns in all the world, ")) 44 print(solution.countSegments("Hello, my, name, is, John")) 45 print(solution.countSegments("love live! mu'sic forever"))