做网站写代码流程西安网站seo推广
434. 字符串中的单词数
题解:
这个问题可以通过遍历字符串,当遇到非空格字符时,判断其前一个字符是否为空格,如果是,则说明这是一个新的单词的开始,计数器加一。最后返回计数器的值即可。
class Solution:def countSegments(self, s: str) -> int:count= 0for i in range(len(s)):if s[i] != ' ' and (i == 0 or s[i-1] == " "):count += 1return count